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

Time:12-14

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.

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

CodePudding user response:

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.

  • Related