指针数组的内存分配 [英] Allocation of memory for Array of Pointers

查看:356
本文介绍了指针数组的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main()

{

int i;

int * a [2];

a = calloc(4,sizeof(* a));

/ *上面的代码我知道不会编译[Lvalue required]。但是为什么

我不能分配空间

我需要存储的所有4个整数* /

for(i = 0; i< 2; i ++)

a [i] = calloc( 2,sizeof(* a));

/ *这个工作正常我知道吗?但为什么不早一个* /

}

main()
{
int i;
int *a[2];
a=calloc(4,sizeof(*a));
/* The above code I know will not compile[Lvalue required] .But why
cant I allocate space
for all 4 integers i need to store */
for(i=0;i<2;i++)
a[i]=calloc(2,sizeof(*a));
/* this works fine I know?But why not the earlier one */
}

推荐答案



原因可能是:

您试图将int *分配给int * *在frist声明中

但是,在第二个stmt中你将int *分配给int *这是一个

有效声明。


-Chandan


smartbeginner写道:
Hi,
The reason might be:
You are trying to assign int * to int ** in the frist statement
however, in second stmt you are assigning int * to int * which is a
valid statement.

-Chandan

smartbeginner wrote:
main()
{
int i;
int * a [ 2];
a = calloc(4,sizeof(* a));
/ *上面的代码我知道不会编译[Lvalue required]。但是为什么
我不能分配空间<对于我需要的所有4个整数存储* /
for(i = 0; i< 2; i ++)
a [i] = calloc(2,sizeof(* a));
/ *这个工作正常我知道吗?但为什么不早一个* /
}
main()
{
int i;
int *a[2];
a=calloc(4,sizeof(*a));
/* The above code I know will not compile[Lvalue required] .But why
cant I allocate space
for all 4 integers i need to store */
for(i=0;i<2;i++)
a[i]=calloc(2,sizeof(*a));
/* this works fine I know?But why not the earlier one */
}






void * calloc(size_t nelem,size_t elsize)


函数calloc返回一个指针,指向一个适当对齐的空间,用于存储任何类型的对象。


a [i ]是一个指向整数的指针,但是a是一个指向空格的指针,它是指向一个整数的指针。

void *calloc(size_t nelem, size_t elsize)

function calloc return a pointer to a space suitably aligned for
storage of any type of objec.

a[i] is a pointer to a integer , but a is a pointer to a space which is
a pointer to a integer.




smartbeginner写道:

smartbeginner wrote:
main()
{
int i;
int * a [2];
a = calloc(4,sizeof(* a));
/ *上面的代码我知道不会编译[Lvalue required]。但是为什么
我不能为所有4个整数分配空间
需要存储* /
for(i = 0; i< 2; i ++)
a [i] = calloc(2,sizeof(* a));
/ *这个工作正常我知道吗?但为什么不早点* /
}
main()
{
int i;
int *a[2];
a=calloc(4,sizeof(*a));
/* The above code I know will not compile[Lvalue required] .But why
cant I allocate space
for all 4 integers i need to store */
for(i=0;i<2;i++)
a[i]=calloc(2,sizeof(*a));
/* this works fine I know?But why not the earlier one */
}




我觉得你真的笑请阅读comp.lang.c的第6节常见问题,
http ://c-faq.com/aryptr/index.html

正如你的建议。


a是一个数组, a [i]是一个指针。

它们根本不一样。



I think you really should go reading the section6 of comp.lang.c FAQ,
http://c-faq.com/aryptr/index.html
as you''v been suggested.

a is an array, a[i] is a pointer.
they are not the same at all.


这篇关于指针数组的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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