java定义无长度数组_如何声明未定义或没有初始大小的数组?

这可以通过使用指针,并使用 malloc 在堆上分配内存来完成 . 请注意,以后无法询问内存块有多大 . 您必须自己跟踪阵列大小 .

#include

#include

#include

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 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值