Home > Software engineering >  What is the right way to initialize double pointer in c
What is the right way to initialize double pointer in c

Time:12-20

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.

CodePudding user response:

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.

CodePudding user response:

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