gpt4 book ai didi

c - 数组条目在 C 中被覆盖

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:12 24 4
gpt4 key购买 nike

我想将整数数组转换为字符串数组。例如,如果 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;
}

最佳答案

问题是 strings[i] = temp; .这分配 tempstrings[i] ,然后 temp是循环 block 范围内的局部变量,在 block 终止后无效。

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

SIZE = 5但是你的数组只有 4 个成员,所以我们有越界访问。我更愿意将其范围限定为它所代表的数据,而不是将其设为全局常量。我还假设这个数组将处理任意数据,因为按原样,它没有使用 i + 1 的优势。在你的循环中。

malloc(12)有足够的空间来容纳 32 位 int 字符串(sizeof char 始终为 1,我们需要空间来容纳 '-''\0' 字符)。正如 this comment 中指出的那样, 你可以使用 sizeof(int) * CHAR_BIT / 3 + 2计算缓冲区的正确大小,其中 CHAR_BITlimits.h 中定义标题。

顺便说一句,有no needmalloc最好使用 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(12);
sprintf(strings[i], "%d", nums[i]);
}

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

free(strings);
return 0;
}

关于c - 数组条目在 C 中被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com