1

How can I iterate over a char ** array? And how can I get the value of each position (get the key1, key2, key3)? I have this:

// Online C compiler to run C program online
#include <stdio.h>
#include <string.h>

int main() {
    
    char **tree_keys = {"key1","key2","key3"};
    printf("Key = %s\n", tree_keys);
    int size = 0;
     int i =0;
   while(tree_keys[i] != '\0'){
       size++;
       i++;
   }
     printf("%s", size);
   

    return 0;
}```

it returns segmentation fault

  • 2
    Does this answer your question? [What does int argc, char \*argv\[\] mean?](https://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean) – anatolyg Nov 01 '20 at 16:50
  • 1
    Three problems: First of all the initialization is not valid; Then `tree_keys` is not a string and can't be used as such (like you do with `printf`); And it's not automatically terminated. Don't use pointers to pointers here, use an *array* of pointers instead: `char const *tree_keys[] = { "key1", "key2", "key3", NULL };` – Some programmer dude Nov 01 '20 at 16:57

1 Answers1

1

First of all, you can't initialize an array of strings this way. Here are two ways to do it:

int string_count = 3;
char **tree_keys = malloc(string_count * sizeof(char *));
if (tree_keys == NULL) exit(1);
tree_keys[0] = "key1";
tree_keys[1] = "key2";
tree_keys[2] = "key3";
char *tree_keys[] = { "key1", "key2", "key3" };

Of course, the second way is preferable to the first one because you don't need to use malloc.

After you have an initialized array you can iterate like so:

int size = 0, string_count = 3;
for (int i = 0; i < string_count; i++) {
    char *ptr = tree_keys[i];
    while (*ptr != '\0') {
        size++;
        ptr++;
    }
}
Jim Morrison
  • 401
  • 4
  • 9