Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help would be appreciated.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading