Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix this code to create an array of strings?

Tags:

arrays

c

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?

like image 495
mko Avatar asked Dec 27 '22 20:12

mko


1 Answers

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.

like image 88
Sergey Kalinichenko Avatar answered Jan 16 '23 19:01

Sergey Kalinichenko