Steven
Steven

Reputation: 27

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.

Upvotes: 2

Views: 312

Answers (2)

4386427
4386427

Reputation: 44329

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. Besides making the code more simple (i.e. only 1 malloc) it also ensures that the whole 2D array is in consecutive memory which may give you better cache performance.

Upvotes: 5

David Grayson
David Grayson

Reputation: 87486

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);

Upvotes: 1

Related Questions