gpt4 book ai didi

c - 在C中打印链表中节点的十六进制内存地址

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:06 25 4
gpt4 key购买 nike

我有一个链表,它接受一个输入字符串并将每个字符串存储在列表的一个节点中。我想打印保存每个字符串的节点的十六进制地址。

我该怎么做?我尝试打印已保存单词的十六进制地址,但我还不知道它是否仍然是节点的相同地址,这是应该打印每个节点的函数:

// print the list
void printList(ListNodePtr currentPtr)
{
// if list is empty
if (isEmpty(currentPtr)) {
puts("List is empty.\n");
}
else {
puts("The list is:");
// while not the end of the list
while (currentPtr != NULL) {
printf("%s %p --> ", currentPtr->data, &currentPtr);

currentPtr = currentPtr->nextPtr;
}
puts("NULL\n");
}
}

这是将每个单词保存在一个节点中的函数

void insert(ListNodePtr *sPtr, char *value)
{
ListNodePtr newPtr = malloc(sizeof(ListNode)+1); // create node

if (newPtr != NULL) { // is space available
newPtr->data= malloc(strlen(value));
strcpy(newPtr->data, value);
newPtr->nextPtr = NULL; // node does not link to another node
ListNodePtr previousPtr = NULL;
ListNodePtr currentPtr = *sPtr;
// loop to find the correct location in the list
while (currentPtr != NULL) {
previousPtr = currentPtr; // walk to ...
currentPtr = currentPtr->nextPtr; // ... next node
}
// insert new node at beginning of list
if (previousPtr == NULL) {
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else { // insert new node between previousPtr and currentPtr
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else {
printf("Not inserted. No memory available.\n" );
}
}

最佳答案

&currentPtr 为您提供指向指针变量 的指针,它不是currentPtr 实际指向的位置。 &currentPtr 的值在循环中不会改变,因为变量本身不会改变位置。

如果您想打印 currentPtr 指向的位置,即节点本身,则打印普通 currentPtr

关于c - 在C中打印链表中节点的十六进制内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52148692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com