user3907480
user3907480

Reputation: 440

How does this pointer typecasting work?

Can anyone please explain how the following code works? I wish to know what is exactly the value returned to variable p and how?

#define MR 3
#define MC 4
int (*p)[MC];
p=(int(*)[MC])malloc(MR*sizeof(*p));

Thanks in advance.

Upvotes: 1

Views: 72

Answers (2)

WhozCraig
WhozCraig

Reputation: 66194

From top to bottom (noting MC 4 and MR 3)

int (*p)[MC];

declares p as a pointer to an array of 4 int.

sizeof(*p)

size of an array of 4 int

MR*sizeof(*p)

3 * (size of an array of 4 int), i.e. 12 contiguous int values.

Finally, the cast:

p=(int(*)[MC])malloc(MR*sizeof(*p));

is simply forcing the underlying void* returned by malloc tothe pointer-type that of the lvalue of the assignment, the pointer p.

In the end, this dynamically allocates an array (dim=3) of arrays (dim=4) of int, in a single dynamic contiguous block of memory. Were this allocated as an automatic variable it would be equivalent to:

int p[MR][MC]

And since you asked how it works. poorly. This is C++. It should be done as:

std::vector<std::array<int,MC>> ar(MR);

Upvotes: 1

Pradhan
Pradhan

Reputation: 16737

p is a variable of type "pointer to int array of size MC". sizeof(*p) is the size of MC ints. Effectively, p is now the pointer to a 2D array with MR rows and MC columns.

Upvotes: 0

Related Questions