Reputation: 573
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);
}
}
Upvotes: 0
Views: 68
Reputation: 477010
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);
}
Upvotes: 1
Reputation: 503
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]));
Upvotes: 1
Reputation: 28870
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 *));
Upvotes: 3