首页 > 解决方案 > 在C中的链表中打印节点的十六进制内存地址

问题描述

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

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

// 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" );
   } 
} 

标签: clinked-list

解决方案


&currentPtr给你一个指向指针变量的指针,它不是currentPtr实际指向的地方。的值&currentPtr不会在循环中改变,因为变量本身不会改变位置。

如果要打印currentPtr指向节点本身的位置,请打印 plain currentPtr


推荐阅读