gpt4 book ai didi

代码无法初始化字符串数组

转载 作者:行者123 更新时间:2023-11-30 19:57:43 25 4
gpt4 key购买 nike

我正在尝试做一些非常简单的事情:建立 10 个八字符字符串的集合,并为每个字符串分配一个简单的默认值。我的代码分配第一个字符串值,但随后出现段错误。代码如下。谁能看出我做错了什么吗?

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


int main() {

char *(names)[8];
int i;
char defstr[] = "none";

*names = malloc(sizeof(char)*8*10);

printf("%s\n",defstr);

printf("defining\n");

for (i=0; i<10; i++) {
strcpy(names[i], defstr);
printf("done with %d, string is %s\n", i, names[i]);
}

printf("now printing\n");

for (i=0; i<10; i++) {
printf("%s\n", names[i]);
}
}

输出为

$> ./a.out
none
defining
Segmentation fault: 11

最佳答案

char *(names)[8];

声明一个8个指针的数组,与

相同
char* names[8];

然后

*names = malloc(sizeof(char)*8*10);

将第一个指针设置为指向 80 个字符的数组。其他 7 个指针仍未初始化。

您似乎想要一个指向数组的指针,这将是

char (*names)[8];

names = malloc(10*sizeof(*names));

关于代码无法初始化字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877542/

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