简体   繁体   中英

How store multiple string or create an array of strings in C, by using 1D array?

Is there any way to get more than 1 string in one array?

#include <stdio.h>
int main (void)
{
        char str[4] = {"Linux", "Ubuntu", "Arch", "Void"};
        for (int i = 0; i < 4; i++) {
                printf("%d", str[i]);
                printf("%s", str[i]);
        }
        printf("%s", str);
}

I just trying to do it. But didn't get it?

How store multiple string or create an array of strings in C, by using 1D array?

The short answer is: You can't

A string in C is by itself a char array (with a zero termination) so there is no way to have multiple strings in a 1D array.

You can make it a 2D array like:

int main()
{
  // Make a 2D array to store
  // 4 strings with 9 as max strlen
  char str[4][10] = {"Linux", "Ubuntu", "Arch", "Void"};

  for (int i=0; i<4; ++i) printf("%s\n", str[i]);
  return 0;
}

Another approach is to use a 1D array of char pointers to string literals - like:

int main()
{
  // Make a 1D array to store
  // 4 char pointers
  char *str[4] = {"Linux", "Ubuntu", "Arch", "Void"};

  for (int i=0; i<4; ++i) printf("%s\n", str[i]);
  return 0;
}

but notice that the strings are not saved in the array. The compiler place the strings somewhere in memory and the array just holds pointers to those strings.

Also notice that in the second example you are not allowed to modify the strings later in the program. In the first example you are allowed to change the strings after the initialization, eg doing strcpy(str[0], "Centos");

BTW: This may be of interrest Are string literals const?

It is possible to store multiple strings in a 1D array - the issue is accessing anything beyond the initial string. For example:

char strs[] = “foo\0bar\0bletch\0blurga”;

The 1D array strs contains 4 strings, but if we pass strs to any library function, only ”foo” will be used.. We would need to maintain a separate array of pointers into strs to access anything beyond the first string:

char *ptrs[] = {strs, &strs[4], &strs[8], &strs[15]};

If you need your strings to be contiguous in memory then this is a valid aproach, but it is cumbersome, and will be a massive pain in the ass if you need to update any of them. Better to use a 2D array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM