Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Apologies if this is simple, but I am new to C. I am trying to create a loop that fills in an empty array of strings with multiple strings. However, at the end, the whole array is being filled with the latest element ! Below is the code:

int main(void)
{
    string array_test[2];
    char string_test[300];

    for (int i = 0; i < 2; i++)
    {
        snprintf(string_test, sizeof(string_test),"Test: %i", i);
        array_test[i] = string_test;
    }

    for (int i = 0; i < 2; i++)
    {
        printf("%s
", array_test[i]);
    }
}

This returns:

Test: 1
Test: 1

But I am expecting:

Test: 0
Test: 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

Because you are using the same buffer to save strings in all iterations. This will make previous strings overwritten by new strings.

Allocate separate buffers for each strings to avoid this.

/* put #include of required headers here */

int main(void)
{
    string array_test[2];
    char string_test[2][300];

    for (int i = 0; i < 2; i++)
    {
        snprintf(string_test[i], sizeof(string_test[i]),"Test: %i", i);
        array_test[i] = string_test[i];
    }

    for (int i = 0; i < 2; i++)
    {
        printf("%s
", array_test[i]);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...