lundi 29 juin 2015

How to initialize an array inside a structure?


I have a structure defined as

struct new{
  int x;
  int y;
  unsigned char *array;
};

where I want array to be an array which is initialized dynamically based on user input. Inside main function:

struct new *sbi;
sbi->array = (unsigned char*)malloc(16 * sizeof(unsigned char));

      for(i=0; i<16; i++)
        {
          sbi->array[i] = 0;
        }

      for(i=0; i<16; i++)
        printf("Data in array = %u\n", (unsigned int)sbi->array[i]);

I am sure I am doing something wrong with the malloc but I am not getting it - it just keeps giving segmentation fault.


Aucun commentaire:

Enregistrer un commentaire