Like this is what the book showed me
int *list = malloc(3 * sizeof(int))
But what’s wrong with this?
int *list = malloc(3)
My understanding says that malloc accepts "size" as a parameter and my goal is to only let pointer list to accept 3 values in it, but then why would I include sizeof(int) when using malloc?
>Solution :
Let’s look at this line of code:
int *list = malloc(3 * sizeof(int))
It creates a pointer to an int, and allocated three times the size of an int worth of memory for it. So we have enough room to store three ints in that block of memory.
I’ll assume one int takes up four bytes of memory. So to store three of them, we need 12 bytes of memory (four bytes per int times three ints). malloc allocates space in bytes, so that will give you 12 bytes of memory (sizeof(int) will return four as there are four bytes per int*).
Now let’s look at the other version:
int *list = malloc(3)
You allocate three bytes of memory. Sadly, one int is four bytes… so you have enough space for 3/4 of an int (again, assuming one int is four bytes). If you wanted to store three ints, you need to allocate memory equal to three times however big an int is, hence 3 * sizeof(int).
*Technically, there are platforms where an int isn’t four bytes. So it is better to write sizeof(int) instead of 4. Don’t worry about that for now, though.