简体   繁体   中英

Why all my elements at the array be the last added value in this C program?

I want to create an array which elements look like this "1A 2A 3A... etc". My problem that every time, the program set all of the elements the value of the last added value. So my final output is "25F 25F 25F..."

Here is my code:

void func() {
    char c[10];
    char s[10];
    char *arr[150];
    int idx = 0;
    for (int i = 1; i <= 25; ++i) {
        for (char j = 'A'; j <= 'F'; ++j) {
            sprintf(c, "%d%c", i,j);
            strcpy(s,c);
            arr[idx++] = s;
            printf("%s", s);
        }
    }

    for (int i = 0; i < 150; ++i) {
        printf("%s\n", arr[i]);
    }
}

here

            arr[idx++] = s;

you make all pointers in the array to point to the array s , so all of them point to the same place and so they all show as the same value in the output.

Something like:

            arr[idx++] = strdup(s);

should make you a copy of the string stored in s at the time you sprintf() it, and having a dynamically allocated array (you will need to call free(arr[idx++]); in another loop later, when you are finished with all these allocations)

The problem is that arr is an array of pointers and all the pointers point to the same place s . So when you change s it seems like all the elements of arr are updated.

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