0

I declare and try to initialise an array of struct pointers. It compiles without error, but this loop always crashes the program after 8 loops:

for(ii = 0; ii < 10; ii++)
    {
    canArray[ii]->AC = 0;
    printf("%d - AC is %d\n", ii, canArray[ii]->AC);
    }

Entire code here:

typedef struct Can
    {
    int AC;
    } Can;


int main (int argc, char* argv[])
    {
        int i, ii;

        Can **canArray= malloc(10 * sizeof(Can[0])); 

        for (i =0; i < 10; i++)
            {
            canArray[i] = (Can*) malloc(sizeof(Can));
            }

        for(ii = 0; ii < 10; ii++)
            {
            canArray[ii]->AC = 0;
            printf("%d - AC is %d\n", ii, canArray[ii]->AC);
            }

    }
Dawson
  • 573
  • 6
  • 24
  • Did you read and understand the answers to the previous question you asked http://stackoverflow.com/questions/16313774/error-incompatible-types-when-initialising-struct-array/16313805#16313805 ? – Paul Hankin May 01 '13 at 09:21

3 Answers3

3

You have some problems with the allocating of memory. You want to allocate space for 10 pointers of Can structure. but you do it wrong.

Can **canArray= malloc(10 * sizeof(Can[0])); 

do it like this:

Can **canArray= malloc(10 * sizeof(Can *)); 
stdcall
  • 27,613
  • 18
  • 81
  • 125
1

Here You need to allocate space for 10 pointers of Can structure. For doing this You need to write

Can **canArray= malloc(10 * sizeof(Can*));

instead of Can **canArray= malloc(10 * sizeof(Can[0]));

anshul garg
  • 473
  • 3
  • 7
1

Can is a type, and Can[0] is also a type, although a bit weird: it's a zero-length array. This isn't actually allowed as a free-standing type, but compilers offer it as an extension.

At any rate, sizeof(Can[0]) is just 0.

You shouldn't say the type inside malloc. Instead, use the variable. This eliminates redundancy. So, your code should be:

Can **canArray = malloc(10 * sizeof canArray[0]); 

for (size_t i = 0; i != 10; ++i)
{
    canArray[i] = malloc(sizeof canArray[i][0]);
    canArray[i]->AC = 0;
    printf("%zu - AC is %d\n", i, canArray[i]->AC);
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084