我试图在 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/