defining and iterating through array of strings in c

When you declare a char sequence with "", null terminator is added.

char myStrings[][10] = { "one", "two", "three", "four", "five" };

for (size_t i = 0; i < sizeof(myStrings) / sizeof(myStrings[0]); i++)
{
    fooThatReceivesOneString(myStrings[i]);
}

Edit - sizeof()

sizeof() returns the size of a variable. It doesn't matter if the variable is an int, array or 2d array.

For example, see the following program

#include <stdio.h>
int main() {
    char myStrings[][10] = { "one", "two", "three", "four", "five" };
    printf("sizeof(myStrings):    %zu\n", sizeof(myStrings));
    printf("sizeof(myStrings[0]): %zu\n", sizeof(myStrings[0]));
    return 0;
}

Which outputs (on my machine):

sizeof(myStrings):    50
sizeof(myStrings[0]): 10

Since each element in the array has the same size (in our case declared to be 10 bytes) we can divide the sizeof the outer array by the sizeof any of its elements to get the number of constituent elements. The simplest option is to just take the first one!


do I need to specify the "10" maximum length?

Yes, apart from the 1st dimension of the array you need to mention all the subsequent dimensions

lso does it automatically create a null ending character after the string?

Yes

I need to pass each string to a function which accepts const char *

You can pass each string like this:

for( i = 0; i < ; i++)
{
  foo(myStrings[i]);
}

Also, You can choose between const char* and char*; since you have declare this as an array it's modifyable; had it been something like

const char *mystrings[] = { " ", " "}; // string literal

then you must have to pass it as const char* because string literals should always be const char*


void loopftn (void)
{
  char *numbers[] = {"One", "Two", "Three", ""}, **n;

  n = numbers;
  while (*n != "") {
    printf ("%s\n",  *n++);
  }
  return;
}
  1. You don't need to have a maximum length.
  2. All strings in C are null-terminated.

In C the statement as shown above **n != "" , is illegal at first sight. It compares a pointer with a string. Even *n != "", would compare the pointer of the string with the "" stack string pointer, not the strings. Should use strcmp or compare first character **n=='\0' or **n==0. Also +*n increments the character int the pointed string, not the pointer to string...

Here is a good implementation:

Code:

static const char* strings[]={"asdf","asdfasdf",0};
const char** ptr = strings;
while(*ptr != 0)
{
   printf("%s \n", *ptr);
   ++ptr;
}

Tags:

C