c - 结构体与链表代码C中动态分配的结构体

标签 c memory struct dynamic-memory-allocation

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

这是主要代码;

#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;
};

最佳答案

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

来自您的声明:

struct strlst_struct *item_ptr, *list_ptr;

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

push( &list_ptr, item_ptr );  

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

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

int x = 5;
int *ptr_to_x;

ptr_to_x = &x;

* 运算符在用于一元运算符时是引用运算符。它允许人们访问存储在给定地址的值。
回到上面的例子,
打印 *ptr_to_x 的值将为您提供 5,即 x 的值。 x(由ptr_to_x表示)地址处存储的值为5。

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

关于c - 结构体与链表代码C中动态分配的结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471186/

相关文章:

c - 如何使用 dtrace 查看调用堆栈

c - 在C中的不同文件中获取标准输出和错误输出

.net - TabControl.Items.Remove(TabItem) 不会释放 TabItem 使用的内存

c - main 之外的函数中的值不会保留在结构中

c - 指针操作期间出现段错误

c - 优化 if 语句在第一次评估后始终具有相同的值

c - 如何停止从C中的文件中读取

Swift:创建指针数组以调用 C 函数

c - 声明还是定义?

c 结构变量赋值中的编译错误