简体   繁体   中英

What is the right way to initialize double pointer in c

As title, I want to know how to initialize double pointer with sizeof a pointer.

For instance

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

for(size_t i = 0; i < rows; i++){
    p[i]=malloc(sizeof ? * cols);
}

What should I fill in ? .

Any help would be appreciated.

It looks like you want p to be an array that can hold pointers, and the number of pointers is rows . So you can allocate memory for p like this:

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

Now if you want p[i] to point to an array that holds cols ints, do this:

p[i] = malloc(sizeof(int) * cols);

What should I fill in?.

In general when you have

X = malloc(sizeof ? * NUMBER);

the ? is to be replaced with the type that X points to. That can simply written as *X .

So the line:

p[i]=malloc(sizeof ? * cols);

is to be:

p[i]=malloc(sizeof *p[i] * cols);

Notice that a 2D array can be created much simpler. All you need is

int (*p)[cols] = malloc(sizeof *p * rows);

Here p is a pointer to an array of cols int . Consequently sizeof *p will be the size of an array of cols int .

Using this VLA based technic means that you can allocate the 2D array using a single malloc

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