gpt4 book ai didi

在 C 中创建一个字符串数组失败,为什么?

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

我试图在 C 中创建一个字符串数组。这是代码:

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

int main()
{
char *foo[100];
strcpy(foo[0], "Testing this");
printf("%s ", foo[0]);

return 1;
}

但是当我编译它时,它就崩溃了。没有错误,什么都没有,它根本不起作用并且中断了。有什么建议吗?当我使用 tri char *foo[10] 时它可以工作,但我不能只使用 10 个字符串

最佳答案

您分配了一个指针数组,但没有分配任何内存供它们指向。您需要调用 malloc 从堆中分配内存。

char *foo[100];
foo[0] = malloc(13);
strcpy(foo[0], "Testing this");

当然,您需要在稍后某个时间用完内存后释放内存。

您的代码调用了所谓的 undefined behavior。 .基本上任何事情都可能发生,包括代码按预期工作。如果带有 char *foo[10] 的版本如您所愿,那完全是运气。

顺便说一句,您的 main() 定义是错误的。它应该是 int main(void)

关于在 C 中创建一个字符串数组失败,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8674663/

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