没有malloc的动态数组?
Dynamic array without malloc?
我正在阅读一些源代码并发现一个基本上允许您将数组用作链表的功能?代码的工作原理如下:
#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.
请记住:在您的程序中,无论您尝试使用什么内存位置,都必须对其进行定义。您必须使用编译时分配(例如标量变量定义),或者对于指针类型,您需要使它们指向某个有效的内存(先前定义的变量的地址)或分配内存运行-时间(使用分配器函数)。使用任意内存位置,不确定,是无效的,会导致UB。
I understand that s points to the beginning of an array in this case
没有指针具有自动存储持续时间并且未被初始化
int *s;
所以它有一个不确定的值并且指向任何地方。
but the size of the array was never defined
程序中既没有声明也没有定义数组。
Why does this work and what are the limitations of it?
这是偶然的。也就是说,当您 运行 它时,它会产生预期的结果。但实际上程序有未定义的行为。
正如我首先在评论中指出的那样,您所做的是行不通的,它似乎行得通,但实际上是undefined behaviour。
In computer programming, undefined behavior (UB) is the result of
executing a program whose behavior is prescribed to be unpredictable,
in the language specification to which the computer code adheres.
因此,它有时 “有效”,有时无效。因此,永远不要依赖这种行为。
如果在 C 中分配一个动态数组那么容易,那么人们会使用 malloc 吗?!尝试使用比 10
更大的值来增加导致 segmentation fault.
的可能性
查看 SO Thread 了解如何在 C 中正确分配和数组。
我正在阅读一些源代码并发现一个基本上允许您将数组用作链表的功能?代码的工作原理如下:
#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.
请记住:在您的程序中,无论您尝试使用什么内存位置,都必须对其进行定义。您必须使用编译时分配(例如标量变量定义),或者对于指针类型,您需要使它们指向某个有效的内存(先前定义的变量的地址)或分配内存运行-时间(使用分配器函数)。使用任意内存位置,不确定,是无效的,会导致UB。
I understand that s points to the beginning of an array in this case
没有指针具有自动存储持续时间并且未被初始化
int *s;
所以它有一个不确定的值并且指向任何地方。
but the size of the array was never defined
程序中既没有声明也没有定义数组。
Why does this work and what are the limitations of it?
这是偶然的。也就是说,当您 运行 它时,它会产生预期的结果。但实际上程序有未定义的行为。
正如我首先在评论中指出的那样,您所做的是行不通的,它似乎行得通,但实际上是undefined behaviour。
In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres.
因此,它有时 “有效”,有时无效。因此,永远不要依赖这种行为。
如果在 C 中分配一个动态数组那么容易,那么人们会使用 malloc 吗?!尝试使用比 10
更大的值来增加导致 segmentation fault.
查看 SO Thread 了解如何在 C 中正确分配和数组。