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

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 does not work:

 char arry_of_string[] = {str1,str2,str3}; 

How to fix it?

+4
source share
5 answers

If you want to create an array of strings, you will be missing an asterisk and trailing 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 to make separate lines:

 char str1[] = "fi"; char str2[] = "se"; char str3[] = "th"; char *arry_of_string[] = {str1,str2,str3}; 

When you use the char x[] = "..." construct, the contents of your string literal (including the zero end) are copied to memory, which you can write, creating the same effect as the char x[] = {'.', '.', ... '\0'} construct char x[] = {'.', '.', ... '\0'} .

+6
source

you can use it as follows: (note that if you want to print an array from char, u must have its terminated '\ 0')

 int main() { char str1[] = {'f','i','\0'}; char str2[] = {'s','e','\0'}; char str3[] = {'t','h','\0'}; char* arry_of_string[] = {str1,str2,str3}; for (int i=0;i<3;i++) { printf("%s\n",arry_of_string[i]); } return 0; } 
+2
source

You are probably looking for pointer instead of a direct array.

 char *arry_of_string[] = {str1,str2,str3}; 

An array is a set of values, a pointer is a list of addresses containing values, so a char pointer is a pointer to the address of arrays containing your strings (character arrays). and breathe

+1
source

you can just use:

 const char *array_of_string[] = {"fi", "se", "th"}; int i; for (i=0;i<3;i++) { printf("%s\n", array_of_string[i]); } 

if you want to be brief ...

+1
source

When you specify the line as

 char* myString = "abcd"; 

It creates a pointer to an array of types and points to the base address or the 0th element of an array of characters. Therefore myString points to. Using char * is useful since c provides a good way to print the entire array using

 printf("%s",myString); 

Also a pointer is useful if you do not know or do not want to specify the length of the char array. Your question must be resolved if you do.

  char *str1 = "fi"; char *str2 = "se"; char *str3 = "th"; char* arry_of_string[] = {str1,str2,str3}; int i; for (i=0;i<3;i++) { printf("%s\n",arry_of_string[i]); } return 0; 

Feel free to mark the answer if you are satisfied.

0
source

All Articles