【发布时间】: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;
};
【问题讨论】:
-
&是“地址”运算符,*是取消引用运算符。我建议阅读许多关于指针如何工作的 C 语言参考资料和文章。
标签: c memory struct dynamic-memory-allocation