C数组条目被覆盖

问题描述 投票:1回答:1

我想将整数数组转换为字符串数组。例如,如果arr[] = {1, 2, 3, 4, 5},我想以arr2[] = {"1", "2", "3", "4", "5"}结尾。该函数可以正常工作,直到退出for循环,在循环中所有数组条目都被最后一个条目的值覆盖。为什么会发生这种情况的任何想法?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 5
int main(){
    int nums[] = {1, 2, 3, 4};
    char **strings = (char **)malloc(SIZE * sizeof(char*));

    for(int i = 0; i < SIZE; i++){
        char temp[20];
        sprintf(temp, "%d", nums[i]);
        strings[i] = temp;
        //prints correct values here
        printf("%s\n", strings[i]);
    }

    for(int i = 0; i < SIZE; i++){
        //prints wrong values here
        printf("%s\n", strings[i]);
    }

    return 0;
}
c arrays string pointers
1个回答
1
投票

问题是strings[i] = temp;。这将temp分配给strings[i],但是temp是作用于循环块的局部变量,并且在该块终止后无效。

您需要为每个字符串提供malloc内存以保存复制的值(完成后将其保存为free)。 tmp也是不必要的,因为我们可以直接将sprintf插入指针。

SIZE = 5,但您的数组只有4个成员,因此我们具有访问权限。我宁愿将此范围限定为它表示的数据,而不是使其成为全局常量。我还假设此数组将处理任意数据,因为按原样,与在循环中使用i + 1相比,它没有任何优势。

[malloc(11)足够用于容纳int字符串的空间(sizeof char始终为1)。

此外,no need强制转换为malloc,在重构期间指针类型发生更改的情况下,最好使用sizeof(*strings)

#include <stdio.h>
#include <stdlib.h>

int main() {
    int nums[] = {1, 2, 3, 4};
    int nums_size = 4;
    char **strings = malloc(nums_size * sizeof(*strings));

    for (int i = 0; i < nums_size; i++) {
        strings[i] = malloc(11);
        sprintf(strings[i], "%d", nums[i]);
    }

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

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.