【发布时间】:2018-09-03 11:17:17
【问题描述】:
我有一个链表,它接受一个输入字符串并将每个字符串存储在列表的一个节点中。我想打印保存每个字符串的节点的十六进制地址。
我该怎么做?我尝试打印保存字的十六进制地址,但我还不知道它是否仍然是节点的相同地址,这是应该打印每个节点的函数:
// 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, ¤tPtr);
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" );
}
}
【问题讨论】:
-
您的
printf参数太少或%ses 太多。 -
除了您的帖子之外:您需要
malloc(strlen(value)+1);来在字符串末尾处以空终止。您应该运行 valgrind 以便在您的代码中找到更多此类错误。 -
currentPtr->data的地址是保存字的地址 -
除此之外,您要打印指针的值,而不是保存指针的变量的地址,因此:
printf("%s %p --> ", currentPtr->data, currentPtr);。另外,你无缘无故地多了一个 %s。 -
这样您就可以打印出您的单词地址,例如:
printf("word address %p of current node: %p", currentPtr->data, currentPtr);
标签: c linked-list