-1

I'm trying to understand the difference between these two snippets. Both of them work fine.

int rows = 4;

int **p = malloc(rows * sizeof(int **)); //it works without type casting

and

int**p = (int **) malloc(rows * sizeof(int*)); // using casting method.

What does sizeof(int**) mean?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Malloc returns a void * which can be converted to any other type without explicit casting. In C that is. The argument for not casting at all (as in the first line you entered) runs back to what happens if you forget to include stdlib.h on certain compilers. The default is to assume malloc returns an int so if you cast you are saying this is fine. – carveone Feb 18 '19 at 22:13
  • One could possibly argue that sizeof(int *) is probably the same as sizeof(int **) and you are getting away with it, but the first line is still wrong and the second line, in C (not C++) doesn't need (and probably should not have) the case to (int **). – carveone Feb 18 '19 at 22:18

1 Answers1

1

To allocate an array of foo_ts, the standard pattern is one of these:

foo_t *p = malloc(count * sizeof(foo_t));
foo_t *p = malloc(count * sizeof(*p));

You either say "give me count items of size s", where the size is either sizeof(foo_t) or sizeof(*p). They're equivalent, but the second is better since it avoids writing foo_t twice. (That way, if you change foo *p to bar *p you don't have remember to change sizeof(foo_t) to sizeof(bar_t).)

So, to allocate an array of int *, replace foo_t with int *, yielding:

int **p = malloc(count * sizeof(int *));
int **p = malloc(count * sizeof(*p));

Notice that the correct size is sizeof(int *), not sizeof(int **). Two stars is too many. The first snippet where you wrote sizeof(int **) is, therefore, wrong. It appears to work, but that's just luck.

Notice also that I did not include an (int **) cast. The cast will work, but it's a bad idea to cast the return value of malloc(). The cast is unnecessary and could hide a subtle error*. See the linked question for a full explanation.


* Namely, forgetting to #include <stdlib.h>.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • The famous C-faq also has the answer to this (http://c-faq.com/malloc/cast.html) along with many other answers to confusing C minutiae. – carveone Feb 18 '19 at 22:20