I want to create an array of strings. Here is the code:
#include <stdio.h>
int main(void){
char str1[] = {'f','i'};
char str2[] = {'s','e'};
char str3[] = {'t','h'};
char arry_of_string[] = {str1,str2,str3};
printf("%s\n",arry_of_string[1]);
return 0;
}
This is the line that doesn't work:
char arry_of_string[] = {str1,str2,str3};
How do I correct it?
If you would like to create an array of strings, you are missing an asterisk, and terminating zeros:
char str1[] = {'f','i','\0'};
char str2[] = {'s','e','\0'};
char str3[] = {'t','h','\0'};
char *arry_of_string[] = {str1,str2,str3};
There is an easier way of doing the individual strings, too:
char str1[] = "fi";
char str2[] = "se";
char str3[] = "th";
char *arry_of_string[] = {str1,str2,str3};
When you use the char x[] = "..."
construct, the content of your string literal (which includes a terminating zero) is copied into memory that you are allowed to write, producing the same effect as char x[] = {'.', '.', ... '\0'}
construct.
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