【问题标题】:Struct vs Dynamically allocated struct in linked list code C链表代码C中的结构与动态分配的结构
【发布时间】:2018-12-30 10:57:36
【问题描述】:

我有一个完整的链表代码,可以反转字符串的内容。我的问题是试图理解“&”运算符和“*”运算符的含义。以及它对代码的意义。

这里是主要代码;

#include "strlst.h"
#include <stdlib.h>
#include <stdio.h>

int main()
{
char letter;
char *string = "dlrow olleh\n";
struct strlst_struct *item_ptr, *list_ptr;

list_ptr = NULL;

for (;*string;string++)
{
    item_ptr = new_item( *string );
    push( &list_ptr, item_ptr );
}

while (list_ptr)
{
    item_ptr = pop( &list_ptr );
    letter = free_item( item_ptr );
    printf( "%c", letter );
}
printf( "\n" );

return 0;
}

如您所见,list_ptr 是在带有“&”运算符的函数中调用的,而 item_ptr 不是。我想知道为什么会这样以及它有什么不同。

我将发布第一个循环所需的功能。第一个函数我很容易理解,看来我们只是将字符'd'设置为item_ptr中的数据,然后将指针设置为NULL。

第二个功能是我感到困惑的地方。我不知道“*”发生了什么以及它对程序做了什么。

第一个函数:

struct strlst_struct *new_item( char character )
{
struct strlst_struct *item_ptr;

item_ptr = malloc( sizeof(struct strlst_struct) );
item_ptr->character = character;
(*item_ptr).next = NULL;

return item_ptr;
}

第二个功能:

void push( struct strlst_struct **list_ptr, 
       struct strlst_struct *item_ptr )
/* Add the item pointed to by item_ptr to the beginning of the list 
   pointed to by list_ptr.
*/
{
item_ptr->next = *list_ptr;
*list_ptr = item_ptr;
}

即使你不理解我提供的上下文,我也不明白什么时候以及为什么在动态分配的结构中使用“*”和“&”。

附言。 strlst_struct 定义为:

struct strlst_struct
{
char character;
struct strlst_struct *next;
};

【问题讨论】:

  • &amp; 是“地址”运算符,* 是取消引用运算符。我建议阅读许多关于指针如何工作的 C 语言参考资料和文章。

标签: c memory struct dynamic-memory-allocation


【解决方案1】:

void push( struct strlst_struct **list_ptr, struct strlst_struct *item_ptr ) 您可以在这里看到 item_ptr attribute 只是一个简单的指针,它保存 strlst_struct 结构的常规元素的地址。
另一方面,list_ptr attribute 是一个双指针。这意味着它保存了一个简单或常规指针的地址,而该指针又保存了一个常规变量的地址。

来自您的声明:

struct strlst_struct *item_ptr, *list_ptr;

这两个指针都不是双指针(它们不保存另一个指针的地址,只是一个常规元素)。当您在此处将这些传递给 push() 函数时:

push( &list_ptr, item_ptr );  

您必须确保将双指针作为第一个参数传递,将普通指针作为第二个参数传递。 因此,&amp;list_ptr 是必需的:它存储指针的地址。

来到运营商:
& 运算符为您提供变量的地址。常见的指针初始化涉及到:

int x = 5;
int *ptr_to_x;

ptr_to_x = &x;

当在一元运算符中使用 * 运算符时,它是延迟运算符。它允许访问存储在给定地址的值。
回到上面的例子,
打印*ptr_to_x 的值会给你 5,或者 x 的值。 x的地址(以ptr_to_x表示)存储的值为5。

请通过一些教程或练习题来强化这个非常重要的概念。

【讨论】:

    猜你喜欢
    • 2019-10-14
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多