2

I've read some similar questions to this but I still can't see where I'm going wrong.

I malloc the pointers and that seems to work OK, but I get an error (incompatible types) on this line:

canArray [i] = (TinCan *) malloc(sizeof(TinCan))

Here is the complete code:

typedef struct TinCan
{
    int date;
    int time;
} TinCan;

int main ()
{
    int i;
    TinCan *canArray = malloc(10 * sizeof(TinCan));

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

2 Answers 2

4

Guessing that you have a typedef struct {...} TinCan; somewhere, then here:

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

You have enough space for 10 TinCan structures, but here:

canArray [i] = (TinCan *) malloc(sizeof(TinCan));

You are trying to allocate space for another TinCan struct.

Do you want:

  1. An array of TinCans? If so, you don't need the loop - the space has already been allocated when you asked for 10 * sizeof(TinCan)

  2. An array of pointers to TinCan structs? If so, change the first line to:

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

    and keep the loop.


Some general comments:

  • You don't need the cast before the malloc() call - see - Do I cast the result of malloc?

  • It's good practice to use sizeof(varname[0]) rather than sizeof(typename), to avoid (or make more obvious) silly mistakes.

  • With the current loop code, you will leave the last TinCan uninitialised - you're creating 10 entries in canArray, but only initialising 9 of them with i < 9. Change that to i < 10, or for extra credit, swap out both for a #define NUMBER_OF_CANS 10

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I understand now. If I want to pass that array now to a method for initialisation, would it look like this? intitialise(canArray**)? It's not working for me.
It doesn't matter. You can have a function initialise an array, or an array of pointers. I would probably go with the first approach (a pointer to 10 TinCans), since the code will be cleaner.
Also, it's important to remember that arrays and pointers aren't the same thing - if that sounds confusing, have a read of c-faq.com/aryptr/aryptr2.html
3

You have declared an array of TinCan structs, but your loop suggests you want an array of pointers to TinCan structs.

Change the declaration of canArray to:

TinCan *canArray[] = malloc(10 * sizeof(TinCan*));

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.