C 中的动态数组

Dynamic Array in C

我正在使用一个数组,我试过这个代码:

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

int main()
{
char **q = (char*)malloc(1*sizeof(char*));
q[0]="So Many Books";
q[1]="So Many Books";
q[2]="So Many Books";
q[3]="So Many Books";
q[4]="So Many Books";
printf("%s\n",q[0]);
printf("%s\n",q[1]);
printf("%s\n",q[2]);
printf("%s\n",q[3]);
printf("%s\n",q[4]);
return 0;
}

为什么编译器没有给我报错? 我只预订了一组字符串中的一个字符串。

我查看了一些资源,例如:

Why is the compiler not giving me an error here

仅仅是因为,这里的问题与任何语法错误无关,它是一个逻辑错误,超出了编译器错误检查的管辖范围。

这里的问题是,除了索引0,任何其他索引在这里都是越界访问。 C 标准中没有任何内容可以 阻止 你这样做,但是访问超出限制的内存会调用 undefined behavior,因此程序输出也是未定义的。什么事情都可能发生。只是不要那样做。

记住,仅仅因为你可以做某事(编写代码来访问超出限制的内存)并不意味着你应该做那。

也就是说,please see this discussion on why not to cast the return value of malloc() and family in C.