понеделник, 11 април 2016 г.

Program Language C: Function to pointer to struct

#include<stdio.h>

typedef struct display display_t;

struct display
{
  int rows;
  int row_symbol_numbers;
  void (*func) (display_t *);
  void (*func2)(display_t *);
};

void func(display_t *pdl1)
{
  printf("Enter\n");
  pdl1->rows = 1;
  printf("%s:%d, pdl1 = %p, pdl1->rows = %d\n", __func__, __LINE__, pdl1, pdl1->rows);
  printf("Exit\n");
}

void func2(display_t *pdl1)
{
  printf("Enter\n");
  pdl1->rows = 2;
  printf("%s:%d, pdl1 = %p, pdl1->rows = %d\n", __func__, __LINE__, pdl1, pdl1->rows);
  printf("Exit\n");
}

int main()
{
  display_t display1;
  display_t *pdisplay1;
  pdisplay1 = &display1;

  pdisplay2->func  = func;   // initialize pointer to func
  pdisplay1->func2 = func2;  // initialize pointer to func2

  if(NULL == pdisplay1->func)
  {
     printf("pdisplay1->func is null!\n");
  }

  if(NULL == pdisplay1->func2)
  {
     printf("pdisplay1->func is null!\n");
  }

  pdisplay1->rows = 14;

  pdisplay1->func(pdisplay1);  // call pointer to function
  printf("%s:%d, pdisplay1 = %p, pdisplay1->func = %p, pdl1->rows = %d\n", __func__, __LINE__, pdisplay1, pdisplay1->func, pdisplay1->rows);

  pdisplay1->func2(pdisplay1);  // call pointer to function
  printf("%s:%d, pdisplay1 = %p, pdisplay1->func2 = %p, pdl1->rows = %d\n", __func__, __LINE__, pdisplay1, pdisplay1->func2, pdisplay1->rows);

  printf("%s:%d, pdl1->rows = %d\n", __func__, __LINE__, pdisplay1->rows);

  return 0;
}

// gcc src.c -o src -std=gnu99