【发布时间】:2019-11-08 17:38:57
【问题描述】:
我想将整数数组转换为字符串数组。例如,如果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, 5};
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]);
}
free(strings);
return 0;
}
【问题讨论】:
-
temp是循环内的局部变量。每次迭代都会超出范围,并且它的生命周期将结束。你所有的指针都指向这个数组,所以在循环之后你的所有指针都将无效。以任何方式使用它都会导致未定义的行为。 -
您的
temp只进行了一次迭代。 -
更不用说你在一个只包含四个元素的数组上迭代了五次。
-
@Someprogrammerdude 是的,这是我的错误,数组应该是 {1, 2, 3, 4, 5}
-
那么请编辑您的问题以解决它。带有不相关错误和问题的minimal reproducible example 会分散您所询问的实际问题的注意力。