How do I create an array of strings in C?

前端 未结 14 2515
野的像风
野的像风 2020-11-22 14:43

I am trying to create an array of strings in C. If I use this code:

char (*a[2])[14];
a[0]=\"blah\";
a[1]=\"hmm\";

gcc gives me \"warning:

相关标签:
14条回答
  • 2020-11-22 15:28

    Here are some of your options:

    char a1[][14] = { "blah", "hmm" };
    char* a2[] = { "blah", "hmm" };
    char (*a3[])[] = { &"blah", &"hmm" };  // only since you brought up the syntax -
    
    printf(a1[0]); // prints blah
    printf(a2[0]); // prints blah
    printf(*a3[0]); // prints blah
    

    The advantage of a2 is that you can then do the following with string literals

    a2[0] = "hmm";
    a2[1] = "blah";
    

    And for a3 you may do the following:

    a3[0] = &"hmm";
    a3[1] = &"blah";
    

    For a1 you will have to use strcpy() (better yet strncpy()) even when assigning string literals. The reason is that a2, and a3 are arrays of pointers and you can make their elements (i.e. pointers) point to any storage, whereas a1 is an array of 'array of chars' and so each element is an array that "owns" its own storage (which means it gets destroyed when it goes out of scope) - you can only copy stuff into its storage.

    This also brings us to the disadvantage of using a2 and a3 - since they point to static storage (where string literals are stored) the contents of which cannot be reliably changed (viz. undefined behavior), if you want to assign non-string literals to the elements of a2 or a3 - you will first have to dynamically allocate enough memory and then have their elements point to this memory, and then copy the characters into it - and then you have to be sure to deallocate the memory when done.

    Bah - I miss C++ already ;)

    p.s. Let me know if you need examples.

    0 讨论(0)
  • 2020-11-22 15:33

    If the strings are static, you're best off with:

    const char *my_array[] = {"eenie","meenie","miney"};
    

    While not part of basic ANSI C, chances are your environment supports the syntax. These strings are immutable (read-only), and thus in many environments use less overhead than dynamically building a string array.

    For example in small micro-controller projects, this syntax uses program memory rather than (usually) more precious ram memory. AVR-C is an example environment supporting this syntax, but so do most of the other ones.

    0 讨论(0)
提交回复
热议问题