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

How to loop through double pointers without knowing size. (C)

How can I loop through this double pointer without knowing it’s size.

char *arr[] = {"ant", "bat", "cat", "dog", "egg", "fly"}; 
char **ptr = arr; // Double pointer 

I tried this but I get an error

while (*ptr){
   printf("%s\n",*ptr);
   ptr+=1;
}

I wan’t something similar to this but with double pointers.

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

char *word = *ptr;
for (int i = 0; *(word + i) != '\0'; i++)
{
   printf("%c", *(word + i));
}

>Solution :

The reason you can do this with strings is because when you assign one to a pointer it automatically has a null byte at the end, so mimic this behavior by adding a NULL element at the end of you string array:

char *arr[] = {"ant", "bat", "cat", "dog", "egg", "fly", NULL};
char **ptr = arr;  // Double pointer

while (*ptr) {
    printf("%s\n", *ptr);
    ptr += 1;
}

This is what is called a sentinel.

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