Search code examples
arrayscinitializationdeclarationc-strings

Store char variables in other char variables in C


I am trying to do the following, create a multy-charr array with other char variables.

char data_info_1[] = "Wellcome.";
char data_info_2[] = "Please";
char data_info_3[] = "If";

int size_line= sizeof(data_info_1)/sizeof(data_info_1[0]);

char data_info[3][size_line]={{data_info_1},{data_info_2},{data_info_3}};

One solution would be the following one, but I am not interested in just putting the string right in the data_info variable

char data_info[3][size_line]={{"Wellcome"},{"Please"},{"If"}};

Could you please explain me why the first thing that I have writen is not valid. And if there is a solution to my problem.

Thanks.


Solution

  • To answer your question, neither of your solutions is correct, you can't initialize a 2D array of chars like that.

    The second option would be valid if it wasn't a variable sized array, i.e.

    char data_info[3][10]={"Wellcome", "Please" ,"If"};
                       ^
                Valid -> fixed size
    

    Assignments like those would be possibe if you had an array of pointers:

    char *data_info[] = {data_info_1, data_info_2, data_info_3}; //1
    

    Or

    const char *data_info[] = {"Wellcome", "Please", "If"}; //2
    

    But these may not be what you need.

    Option 1 will contain pointers to the original strings, any changes made to them through those pointers will be reflected in the original strings.

    Option 2, the pointers are being initialized with string literals and those can't be changed, that's why I added the const qualifier as a metter of safety.

    If neither of these constrains work for you, you'll need to copy the strings with something like strcpy, strncpy or better yet memcpy:

    #include <string.h>
    //...
    memcpy(data_info[0], data_info_1, sizeof data_info_1);
    memcpy(data_info[1], data_info_2, sizeof data_info_2);
    memcpy(data_info[2], data_info_3, sizeof data_info_3);