0

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;
}
1
  • I found one line missing. Now it has everything. Commented Sep 12, 2022 at 3:52

2 Answers 2

1

arr1 has a type of char*[4].

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

Sign up to request clarification or add additional context in comments.

2 Comments

Does it mean I cannot get the number of elements of sub array using master_array?
Correct, you cannot figure out the size of an array unless it is statically allocated, and you use the literal name of that variable. Because everywhere else, an array is just a pointer to the first element.
1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.