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);
            }

    }
1

3 Answers 3

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 *)); 
Sign up to request clarification or add additional context in comments.

Comments

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]));

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.