Search code examples
carrayspointersstructpointer-to-array

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.


Solution

  • You're declaring sbi as a pointer to struct new, but never allocating memory to it. Try this:

    struct new *sbi;
    sbi = malloc(sizeof(struct new));
    

    Also, don't cast the results of malloc, as that can mask other errors, and don't forget to check the return value of malloc.