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));
    }
}
Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
Dawson
  • 573
  • 6
  • 24

2 Answers2

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

Community
  • 1
  • 1
Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
  • 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. – Dawson May 01 '13 at 06:46
  • 1
    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 `TinCan`s), since the code will be cleaner. – Timothy Jones May 01 '13 at 06:48
  • 1
    Also, it's important to remember that arrays and pointers aren't the same thing - if that sounds confusing, have a read of http://c-faq.com/aryptr/aryptr2.html – Timothy Jones May 01 '13 at 06:50
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*));
Paul Hankin
  • 54,811
  • 11
  • 92
  • 118