gpt4 book ai didi

c - 在动态分配的数组中使用 sprintf 时出现段错误

转载 作者:行者123 更新时间:2023-12-02 02:14:09 25 4
gpt4 key购买 nike

我正在将整数转换为字符串并将它们添加到动态分配的数组中。问题是它导致了段错误。我不明白为什么会发生这种情况。

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

int main() {
char *x = malloc(10 * sizeof(char));
x[0] = malloc(10 * sizeof(char));
sprintf(x[0],"%d",10);

for(int i = 0; i < 10;i++){
free(x[i]);
}

free(x);
return 0;
}

最佳答案

要分配一个元素为char*的数组,指向该数组的指针应该是char**,而不是char*

此外,您不得使用通过 malloc() 分配且未初始化的缓冲区中的值。这些值是不确定的,使用它们会调用未定义的行为

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

int main() {
/* correct type here (both variable and allocation size) */
char **x = malloc(10 * sizeof(char*));
x[0] = malloc(10 * sizeof(char));
sprintf(x[0],"%d",10);

/* initialize the other elements to pass to free() */
for (int i = 1; i < 10; i++) x[i] = NULL;

for(int i = 0; i < 10;i++){
free(x[i]);
}

free(x);
return 0;
}

关于c - 在动态分配的数组中使用 sprintf 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67366162/

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