这可以通过使用指针并使用malloc 在堆上分配内存来完成。
请注意,以后无法询问该内存块有多大。您必须自己跟踪数组大小。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
/* declare a pointer do an integer */
int *data;
/* we also have to keep track of how big our array is - I use 50 as an example*/
const int datacount = 50;
data = malloc(sizeof(int) * datacount); /* allocate memory for 50 int's */
if (!data) { /* If data == 0 after the call to malloc, allocation failed for some reason */
perror("Error allocating memory");
abort();
}
/* at this point, we know that data points to a valid block of memory.
Remember, however, that this memory is not initialized in any way -- it contains garbage.
Let's start by clearing it. */
memset(data, 0, sizeof(int)*datacount);
/* now our array contains all zeroes. */
data[0] = 1;
data[2] = 15;
data[49] = 66; /* the last element in our array, since we start counting from 0 */
/* Loop through the array, printing out the values (mostly zeroes, but even so) */
for(int i = 0; i < datacount; ++i) {
printf("Element %d: %d\n", i, data[i]);
}
}
就是这样。以下是对为什么会起作用的更复杂的解释:)
我不知道你对 C 指针了解多少,但 C 中的数组访问(如 array[2])实际上是通过指针访问内存的简写。要访问data 指向的内存,您可以编写*data。这称为取消引用指针。因为data 是int * 类型,那么*data 是int 类型。现在来看一条重要信息:(data + 2) 的意思是“将 2 个整数的字节大小添加到 data 指向的地址”。
C 中的数组只是相邻内存中的一系列值。 array[1] 就在 array[0] 旁边。因此,当我们分配一大块内存并希望将其用作数组时,我们需要一种简单的方法来获取内部每个元素的直接地址。幸运的是,C 也允许我们在指针上使用数组表示法。 data[0]和*(data+0)意思一样,即“访问data指向的内存”。 data[2] 表示*(data+2),访问内存块中的第三个int。