How do we create a string array in C? If I want to put a bunch of words in an array, what is the correct way?
char array[] = {'orange', 'banana', 'kiwi', 'apple', 'pineapple'};
Thanks
How do we create a string array in C? If I want to put a bunch of words in an array, what is the correct way?
char array[] = {'orange', 'banana', 'kiwi', 'apple', 'pineapple'};
Thanks
It is not entirely clear what you are looking to do, but a string in C is actually a char *
, terminated by the NUL
character '\0'
. In other words, a single char
is a character–where a string is an array of char
.
As an example, the following are equivalent definitions of strings.
char hello[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char hello[] = "Hello";
Note that in hello[size]
, in this case size = 6
, size
needs to be at least the size of the string, including the null terminator '\0'
.
As I said previously, it is not completely clear what you are trying to do–if you want to build an array of strings (not the question asked) then I will gladly help you in doing so.
Tutorials on using strings and string.h are vastly available on the web, but I suggest you look for a more comprehensive C course (Harvard's CS50 is a good place to start, and is free).
Good luck,
Alexandre.
Here is a complete C program that declares a string and prints it:
#include<stdio.h>
int main() {
char name[] = "John Q Public"; //declare a string
printf("%s\n", name); //prints "John Q Public"
}
Declaring strings in C is easy: it's just an array of char.