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

标签 c arrays string pointers

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

相关文章:

fread() 可以检测空字符吗?

c - 二维数组添加额外的字符

c - 从 C 中的文件读取后,在字符串后面放置一个空值?

java - 以最快的方式从整数数组中删除子数组?

android - fopen() 不重置文件

javascript - 从对象中获取元素并与数组进行比较 - Jquery

c++ - 两个相同大小(和长度)的数组是否具有相同的元素偏移量?

python - 如何从一串相连的日期中获取日期

Python:在最后一个小写字母处拆分字符串

计算字符串中某个单词出现次数的C代码