之间的差异*列表和**列表 [英] Difference Between *list and **list

查看:135
本文介绍了之间的差异*列表和**列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个结构:

typedef struct A
{
   char c[100];
}A;

然后,我创建一个

Then I create a

sizeOfA = 5000;
A *list = (A*) malloc(sizeOfA * sizeof(A));

列表[我] 指向一个结构?

或者,如果我想要一个指针结构,我应该做的。

Or if I want a pointer to the struct, should I do

A **list = (A**) malloc (sizeOfA * sizeof(A*);

<击>现在让我们说我创建使用列表 A *名单(这是我做的话)。我怎么会创造​​5000指针,并使其指向列表?

Now let's say I created the list using A *list (which I did already). How would I create 5000 pointers and make them point to the elements on the list?

p0 -> list[0]
p1 -> list[1]
..
..
p[n] -> list[n]

来回几次,我注意到,排序的三分球有很大的帮助后。

为了公平起见,我将发布编辑上面作为一个单独的问题。

To be fair I will post the edit above as a separate question.

推荐答案

这条语句之后:

A *list = (A*) malloc(sizeOfA * sizeof(A));

列表是一个指向一个内存块的起始位置,可容纳类型的 sizeOfA 元素结构A 。因此, *名单的类型为结构A ,同样,列表[我] 的类型结构A ,不是指针到结构A的(这将是列表+ I )。

list is a pointer to the starting location of a memory block that can hold sizeOfA elements of type struct A. Thus, *list is of type struct A, and similarly, list[i] is of type struct A, not pointer to struct A (that would be list+i).

如果你想列表[我] 是一个指向结构A ,那么你的第二件$的C $ C.将很正确的,因为你有足够的空间分配的存储空间来保存 sizeOfA 指针结构A 。请注意,您只分配空间来存放指针,而不是实际的结构A 实例。尝试读取列表[I] - 方式&gt;ç将导致不确定的行为

If you want list[i] to be a pointer to struct A, then your second piece of code would be the correct one, since you're allocating a memory location with enough space to hold sizeOfA pointers to struct A. Note that you are only allocating space to hold pointers, not actual struct A instances. Attempting to read list[i]->c will result in undefined behavior.

这篇关于之间的差异*列表和**列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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