结构体指针初始化错误:为何struct Link * temp = cap;无法输出链表赋值内容?
Hey AndyE, let's figure out why that struct Link * temp = cap; line isn't showing the values you assigned to your linked list. There are a handful of common mistakes that cause this—let's walk through them step by step:
Your
cappointer isn't actually pointing to the head of your populated list
It's easy to mess up the initial pointer assignment. For example, if you initializedcapasNULLbut forgot to update it when adding the first node, or accidentally overwrotecaplater in your code (like pointing it to a middle node or freeing it), thentempwill just inherit that broken pointer. No valid node means no values to output.You skipped assigning values to your nodes' data fields
Allocating memory for a node withmalloconly gives you raw, uninitialized memory—you have to explicitly set the data values. If your code looks like this:struct Link *new_node = malloc(sizeof(struct Link)); // Oops! No line like new_node->data = 42; here new_node->next = cap; cap = new_node;Then even though
temppoints tocap, the "values" you're trying to print are just garbage memory values.You're printing the wrong thing (or using incorrect syntax)
Double-check how you're outputting the values. If you're printingtempdirectly, that's just the memory address of the node, not its data. Make sure you're accessing the correct field in your struct. For example, if your struct is defined as:struct Link { int value; struct Link *next; };You need to use
printf("%d\n", temp->value);instead ofprintf("%d\n", temp);or a misnamed field liketemp->data.Your linked list memory was corrupted or freed prematurely
If you calledfree()oncapor any nodes before assigningtemp, or had an out-of-bounds write that messed up the list's memory,tempwill point to invalid memory. This can lead to garbage output or even program crashes.
Here's a quick working example to compare against your code:
#include <stdio.h> #include <stdlib.h> struct Link { int data; struct Link *next; }; int main() { struct Link *cap = NULL; // Add first node struct Link *first_node = malloc(sizeof(struct Link)); first_node->data = 15; first_node->next = NULL; cap = first_node; // Add second node struct Link *second_node = malloc(sizeof(struct Link)); second_node->data = 30; second_node->next = cap; cap = second_node; // Traverse and print values struct Link *temp = cap; while (temp != NULL) { printf("Node value: %d\n", temp->data); // Will print 30, then 15 temp = temp->next; } // Clean up memory temp = cap; while (temp != NULL) { struct Link *next_node = temp->next; free(temp); temp = next_node; } return 0; }
If you can share a bit more of your code (like how you initialized the list, added nodes, and tried to print the values), I can help pinpoint the exact issue.
内容的提问来源于stack exchange,提问作者AndyE

