Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

c - Why the for loop is filling the whole array with the latest string?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...