Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining and iterating through array of strings in c

Tags:

c

How can I define an array of string in c then iterate with a loop through the items in the array?

So far I have

char myStrings[][10] = { "one", "two", "three", "four", "five" };
// do I need to specify the "10" maximum length?
// also does it automatically create a null ending character after the string?

int i = 0;
for( i = 0; i < ; i++)
{
// I need to pass each string to  a function which accepts
// const char *
}
like image 669
user391986 Avatar asked Jul 25 '11 05:07

user391986


People also ask

Can you define an array of strings?

The string is a collection of characters, an array of a string is an array of arrays of characters. Each string is terminated with a null character. An array of a string is one of the most common applications of two-dimensional arrays.

Can we use for loop in string in C?

Use strlen() to get the length of the string. for(int i = 0; i < strlen(full_name); i++) { printf("%c", full_name[i]); } Since the string is terminated by '\0', which is 0 in ASCII value, you can also use full_name[i] != 0 for the condition.

What is iterating through an array?

Iterating over an array means accessing each element of array one by one. There may be many ways of iterating over an array in Java, below are some simple ways. Method 1: Using for loop: This is the simplest of all where we just have to use a for loop where a counter variable accesses each element one by one.


2 Answers

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, we can divide the sizeof an array with the sizeof the first element to get the amount of elements in the array.

like image 50
MByD Avatar answered Sep 21 '22 23:09

MByD


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.
like image 24
Engineer Avatar answered Sep 21 '22 23:09

Engineer