gpt4 book ai didi

C char 双指针

转载 作者:行者123 更新时间:2023-11-30 20:44:06 25 4
gpt4 key购买 nike

这可能看起来很愚蠢,但我不明白发生了什么......

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

/*
gcc -o test test.c -std=c99 && time ./test

*/


int main(int argc, char **argv)
{
char **s;
s = malloc(10);
s[0] = malloc(100);
s[1] = malloc(100);
s[2] = malloc(100);
s[3] = malloc(100);
s[4] = malloc(100);
s[5] = malloc(100);
s[6] = malloc(100);
s[7] = malloc(100);
s[8] = malloc(100);
s[9] = malloc(100);

strcpy(s[0],"test");
strcpy(s[1],"test");
strcpy(s[2],"test");
strcpy(s[3],"test");
// strcpy(s[4],"test");

printf("%s", s[0]);

return 0;
}

如果我取消注释 strcpy(s[4],"test"); 我会遇到段错误。如果我 malloc 149 而不是 10,则通过将字符串复制到 [20] 元素会出现段错误。我最近一年都在用 c 编码,这是我第一次真正感到沮丧......

有人可以解释一下为什么会发生这种情况吗?

编辑

好吧,我的错误。怎么样:

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

/*
gcc -o test test.c -std=c99 && time ./test

*/


int main(int argc, char **argv)
{
char **ar = NULL;
ar = malloc(sizeof(**ar) * 10);

for (int i = 0; i < 10; i++)
{
char ic[2];
sprintf(ic, "%d", i);
int l = strlen(ic);
ar[i] = (char*)malloc(sizeof(*ar[i]) * (l + 1));
strcpy(ar[i], ic);
// asprintf(&(ar[i]), "%d", i);
printf("%s\n", ar[0]);
}

return 0;
}

获取如下输出:

0
0
0
0
�@
�@
�@
�@
�@
�@

最佳答案

更改为s = malloc(10 * sizeof (char *))。您有 10 个指针的数组(通常每个指针 4 个字节),但只分配了 10 个字节。

关于C char 双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32632940/

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