Home > Software engineering >  array of array of strings in c program
array of array of strings in c program

Time:09-12

It seems I'm confused with how to use array of strings in c code. Here, what I wanted to do is making a master_array which includes all other array of strings in.

I made a code like below. And the output is

 arr1[1] = pear
 arr2[1] = lettuce
 arr3[1] = Smith
 master_array[1][2] = onion
 sizeof(arr1) = 4
 sizeof(master_array[0]) = 1

Except for the last one, everything was as expected. I expected sizeof(master_array[0]) = 4. But the result was 1.

Would someone point out what I am confused with?

#include <stdio.h>

int main(void)
{
   char *arr1[] = {"apple", "pear", "banana", "melon"};
   char *arr2[] = {"carrot", "lettuce", "onion", "spinach"};
   char *arr3[] = {"Tom", "Smith", "Dave", "John"};
   char **master_array[] = {arr1, arr2, arr3};

   printf("arr1[1] = %s\n", arr1[1]);
   printf("arr2[1] = %s\n", arr2[1]);
   printf("arr3[1] = %s\n", arr3[1]);
   printf("master_array[1][2] = %s\n", master_array[1][2]);

   printf("sizeof(arr1) = %ld\n", sizeof(arr1)/sizeof(char *));
   printf("sizeof(master_array[0]) = %ld\n", sizeof(master_array[0])/sizeof(char *));

   return 0;
}

CodePudding user response:

arr1 has a type of char*[4].

However, master_array[0] has a type of char **, not char*[4].

CodePudding user response:

This line misleads:

printf("sizeof(master_array[0]) = %ld\n", sizeof(master_array[0])/sizeof(char *));

Because it says it is printing sizeof master_array[0] but is isn't. It is printing size of master_array[0] / sizeof(char *).

It helps to realize that C doesn't really have strings - instead String functions expect a pointer to the first character of a string, and for the string to be terminated with the null character (byte value 0).

  • Related