我正在阅读一些源代码,发现一个功能基本上允许您将数组用作链表?该代码的工作原理如下:
#include <stdio.h>
int
main (void)
{
int *s;
for (int i = 0; i < 10; i++)
{
s[i] = i;
}
for (int i = 0; i < 10; i++)
{
printf ("%d\n", s[i]);
}
return 0;
}
我明白 s
在这种情况下指向数组的开头,但从未定义数组的大小。为什么这样做,它的局限性是什么?内存损坏等
最佳答案
Why does this work
它没有 ,它似乎工作(这实际上是运气不好)。
and what are the limitations of it? Memory corruption, etc.
Undefined behavior.
请记住:在您的程序中,无论您尝试使用什么内存位置,都必须对其进行定义。您要么必须使用编译时分配(例如,标量变量定义),要么对于指针类型,您需要使它们指向某个有效内存(先前定义的变量的地址),或者在以下位置分配内存运行时(使用分配器函数)。使用任何不确定的任意内存位置都是无效的,并且会导致 UB。
关于arrays - 没有malloc的动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65357233/