0

I have the following code:

int main() {
    char** a = {"bob", "alex", "john"};
    for (int i = 0; i < 3; i++) {
        printf('%d', sizeof(a[i]));
    }
}

What I try to do here, is to initialize an array of string, iterate through it and print the size for each word of it. But I get segmentation error. What is wrong with my approach ?

Rustem Sadykov
  • 113
  • 1
  • 8
  • I recommend you to see accepted answer at https://stackoverflow.com/questions/33746434/double-pointer-vs-array-of-pointersarray-vs-array/33748099 – aulven Apr 26 '20 at 06:58
  • Does this answer your question? [Double pointer vs array of pointers(\*\*array vs \*array\[\])](https://stackoverflow.com/questions/33746434/double-pointer-vs-array-of-pointersarray-vs-array) – madteapot Apr 26 '20 at 11:53

1 Answers1

4

Here is a working code:

#include <stdio.h>
int main() {
    char* a[3] = {"bob", "alex", "john"};
    for (int i = 0; i < 3; i++) {
        printf("%d\n", strlen(a[i]));
    }
}

Notice that the differences are char* a[3] instead of char**, "%d" instead of '%d' and strlen instead of sizeof.

Mahmood Darwish
  • 536
  • 3
  • 12