Reputation: 23
I am by no means a master of the C language, nor am i going to claim to be. But I was pretty sure I understood pointers until I came across these two very different implementations that the author claimed would have the same outcome. Im just not seeing it. Can somebody please explain to me what each of these are doing?
int (*AA)[4];
AA = malloc(sizeof(int[4])*size);
and the 2nd one:
int *BB;
BB = (int *)malloc(size*sizeof(int));
From my current understanding, If i wanted to make the 2nd one in c++, it is equivalent to:
int *CC;
CC=new int[size]
Is this assumption Correct?
Upvotes: 1
Views: 137
Reputation: 23236
comments notwithstanding, Given your code:
For illustration, here is what is shown when in debug mode looking at what was created: (ANSI C99 compiler, 32bit build)
At the very least, understanding fully what your author meant when stating same outcome is important.
Also illustrates why the use of calloc()
as opposed to malloc()
might be a good option (C99).
The second part question: C++ version
int* BB = new int[size];
is valid.
Upvotes: 0
Reputation: 574
First part:
int (*AA)[4];
defines AA to be a pointer to an int[4].
AA = malloc(sizeof(int[4])*size);
allocates storage for size
int[4]
s
Second part:
int *BB;
defines BB to be a pointer to an int.
BB = (int *)malloc(size*sizeof(int));
allocates storage for size
int
s, then unnecessarily casts the result, thereby introducing a potential error you won't get warned about (namely, if the prototype for malloc() is not in scope).
Therefore, the result is arguably different
Upvotes: 3