指针如何获取变量,数组,指针,结构的地址

时间:2014-08-08 10:38:32

标签: c arrays pointers linked-list

我的链接列表计划的代码:This is the code I saved on github

知道指针总是接受变量的地址。因此,如果某人正在编写数组的名称,则意味着该数组的第一个元素的地址。好的,这是正确的地址所以我们不需要在数组名称前面写&。但如果是其他任何事情,那么我们必须使用&标志。因此,如果int我们在其前面写了&个符号。但是在结构的情况下,也是某种自定义尺寸的变量?

数组的代码可能如下所示:

int arr[] = {34,234,6234,346,2345,23};
int i;
for(i=0; i<(sizeof(arr)/arr); i++) 
     int *pointer = arr+i; //Now pointer can point to all the member array one by one

int的代码可能如下所示:

int a = 5; 
int *pointer = &a; 

但是如果我有两个指针(head&amp; temp)到struct node类型的结构。现在我正在为节点编写代码。

struct node {
    int data; 
    struct node *next;   // this is pointer to next element in the Linked List
};

现在最初head为NULL,即没有指向任何东西     head = NULL;

但是,如果这样做,首先插入链表:

head = temp;       // both are pointers

知道head只能把地址当作一个指针但temp不是一个数组所以如果写这个写temp就不代表那个结构temp的地址

我应该这样做吗

head = &temp

实际获取临时结构(指针)的地址?

我感觉我们做head = temp并且数组temp之类的有效原因是类型结构节点的指针。所以写temp只意味着内存中临时指针的地址。现在head指针的地址为temp&amp;指向head有什么?

指向headtemp地址的head现在是否有临时地址。我猜是指向和拥有不同。

3 个答案:

答案 0 :(得分:3)

要解释我的评论,请参阅以下粗略图纸:

head = temp的情况下,它看起来像

+------+
| temp | --\
+------+    \     +----------------+
             >--> | your structure |
+------+    /     +----------------+
| head | --/
+------+

这意味着headtemp都指向同一个地方。


如果你另一方面做head = &temp(并且编译器允许),它看起来像

+------+      +------+      +----------------+
| head | ---> | temp | ---> | your structure |
+------+      +------+      +----------------+

也就是说,head指向temp,而不指向您的结构。

答案 1 :(得分:2)

headtemp都属于struct Node*类型。将temp分配给head表示head指向与temp指向的位置相同的位置。 &temp是指向temp类型的struct NODE变量的地址,即struct Node**

temp&temp都属于不同类型。编译器应该提高分配的意义

head = &temp;  // assigning incompatible pointer without cast

答案 2 :(得分:1)

如果是单一变量,intchar运营商的地址是否为arr[i] = *(arr + i)arr[0] = *(arr + 0) = *(arr)。用于引用该变量。在整数数组的情况下,数组的名称arr [],即arr本身表示数组的第一个元素的地址。请参阅下面的指针算术运算数组内部如何执行:

要引用我们编写的第{i}个元素head 所以,temp

但在您的情况下,struct node*head = temphead类型的指针。使用&amp;操作员将temp的地址分配给head将首先被编译器允许给出一个强制转换错误,而且它也不能满足你的目的。你应该做的是temp,这会使struct node和{{1}}指向{{1}}。