How do I fix this code to create an array of strin

2020-04-08 01:37发布

问题:

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?

回答1:

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.



回答2:

you can use it like this:(notice that if you want to print an array of char, u must have it termitated by '\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;

}


回答3:

You are probably looking for a pointer here rather than a direct array.

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

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



回答4:

you could 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 concise...



回答5:

When you specify the string as

char* myString = "abcd";

It creates a pointer of type array and points to the base address or the 0th element of the character array. So myString points to a. Using a char* is useful because c provides a good way of printing out the entire array using

printf("%s",myString);

Also pointer is useful to use when you dont know or dont want to specify the length of the char array. Your question should be solved if you do this

  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 question answered if you are satisfied.



标签: c arrays