c - 指针如何获取变量、数组、指针、结构的地址

标签 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; 

但是如果我有两个指向 struct node 类型的结构的指针(head 和 temp)。现在我正在编写node的代码。

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

现在 head 最初是 NULL,即不指向任何东西 头=空;

但是在第一次插入链表时,如果这样做:

head = temp;       // both are pointers

知道 head 只能获取地址,因为它是一个指针,但 temp 不是一个数组,因此如果写入此内容 temp 并不意味着它是该结构 temp 的地址

我应该这样做

head = &temp

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

我有一种感觉,我们这样做了head = temp,并且像数组temp这样的有效原因是类型结构节点的指针。所以写temp就意味着temp指针在内存中的地址。现在 head 指针具有 temp 的地址并指向 head 的地址?

head 是否指向 temp 的地址,或者 head 现在有 temp 的地址。我想指向和拥有是不同的。

最佳答案

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

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

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

这意味着 headtemp 都指向同一个位置。

<小时/>

如果您另一方面执行 head = &temp (并且编译器允许这样做),它将看起来像

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

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

关于c - 指针如何获取变量、数组、指针、结构的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25201593/

相关文章:

c++ - 双自由或腐败(fasttop): 0x000000000063d070 *** c++ sieve program

c - 递归反转单链表的函数中的段错误

c - 为什么使用_PROTOTYPE头文件

java - 使用数组查找 2 个列表之间的最大数字

c++ - 如何使用包含大量数据的类元素处理 STL 容器

c++ - 变量中的数据不一致

c++ - NULL 指针的取消引用是否也等于 NULL?

c - scanf: "%[^\n]"跳过第二个输入,但 "%[^\n]"不会。为什么?

c - 在函数体和函数头之间声明的变量

javascript - 如何使用 Json 和 Javascript 解决 PHP 数组问题