可以使用malloc()定义数组的大小吗? [英] Can malloc() be used to define the size of an array?

查看:311
本文介绍了可以使用malloc()定义数组的大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里考虑以下代码示例:

Here consider the following sample of code:

int *a = malloc(sizeof(int) * n);

此代码可以用于定义一个包含n个整数的数组吗?

Can this code be used to define an array a containing n integers?

推荐答案

int *a = malloc(sizeof(int) * n);

此代码可以用于定义一个包含n个整数的数组吗?

Can this code be used to define an array a containing n integers?

这取决于您定义数组"的含义.

That depends on what you mean by "define an array".

这样的声明:

int arr[10];

定义一个命名数组对象.您的指针声明和初始化没有.

defines a named array object. Your pointer declaration and initialization does not.

但是,malloc调用( if 成功,并返回非NULL结果, if n > 0)将创建一个匿名数组对象在运行时.

However, the malloc call (if it succeeds and returns a non-NULL result, and if n > 0) will create an anonymous array object at run time.

但是它不会定义数组a". a pointer 对象的名称.假设malloc调用成功,则a将指向数组对象的初始元素,但它本身不是数组.

But it does not "define an array a". a is the name of a pointer object. Given that the malloc call succeeds, a will point to the initial element of an array object, but it is not itself an array.

请注意,由于数组对象是匿名的,因此您无法对sizeof应用任何内容,也无法从指针中检索数组对象的大小.如果您需要了解数组的大小,则需要自己进行跟踪.

Note that, since the array object is anonymous, there's nothing to which you can apply sizeof, and no way to retrieve the size of the array object from the pointer. If you need to know how big the array is, you'll need to keep track of it yourself.

(一些评论建议malloc调用分配的内存可以容纳n整数对象,但不能容纳数组.如果是这种情况,那么您将无法访问创建的数组对象.请参见 N1570 6.5. 6p8用于定义指针添加,而7.22.3p1用于描述malloc调用如何创建可访问数组.)

(Some of the comments suggest that the malloc call allocates memory that can hold n integer objects, but not an array. If that were the case, then you wouldn't be able to access the elements of the created array object. See N1570 6.5.6p8 for the definition of pointer addition, and 7.22.3p1 for the description of how a malloc call can create an accessible array.)

这篇关于可以使用malloc()定义数组的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆