简体   繁体   中英

Dynamic memory allocation and pointers?

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?

To allocate an array of foo_t s, 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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM