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 *
}
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.
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.
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.
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.
void loopftn (void)
{
char *numbers[] = {"One", "Two", "Three", ""}, **n;
n = numbers;
while (*n != "") {
printf ("%s\n", *n++);
}
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With