0

为什么打印语句返回 null?

#include <stdio.h>>
#include <stdlib.h>

struct Node
{
    char abbreviation;
    double number;
    struct Node *next;
};

void insert(char abbreviation, double number, struct Node *head) {
    struct Node *current = head;
    while(current->next != NULL)
    {
        current = current->next;
    }

    struct Node *ptr = (struct Node*)malloc(sizeof(struct Node));
    ptr->abbreviation = abbreviation;
    ptr->number = number;
    current->next = ptr;

    return;
}

int main(int argc, char* argv[]) {
    struct Node *head = (struct Node*)malloc(sizeof(struct Node));
    insert('n',456,head);
    printf("%s\n", head->abbreviation);
}
4

5 回答 5

3

您正在创建一个 head->next 指向的节点,然后在那里插入值。您永远不会在头节点本身中设置任何值。

于 2013-03-21T04:03:17.377 回答
2

abbreviation是一个字符,而不是一个字符串。你想要printf("%c\n", head->abbreviation);

于 2013-03-21T03:58:36.147 回答
0

要添加到UncleO 的 answer中,在调用insert()您的 之前main(),将head->abbreviation和设置head->number为所需的值并初始化head->next为 NULL。

于 2013-03-21T04:46:40.207 回答
0

在此处查看更改:

#include <stdio.h>
#include <stdlib.h>

struct Node
{
char abbreviation;
double number;
struct Node *next;
};

void insert(char abbreviation, double number, struct Node *head) {
struct Node *current = head;
while(current->next != NULL)
{
current = current->next;
}

struct Node *ptr = (struct Node*)malloc(sizeof(struct Node));
ptr->abbreviation = abbreviation;
ptr->number = number;
current->next = ptr;

return;
}

int main(int argc, char* argv[]) {
struct Node *head = (struct Node*)malloc(sizeof(struct Node));
insert('n',456,head);
insert('m',453,head);
printf("%c\n", head->next->abbreviation);
printf("%c\n", head->next->next->abbreviation);
}
于 2013-03-21T07:30:57.447 回答
0

请尝试此代码。

#include <stdio.h>>
#include <stdlib.h>
struct Node
{
    char abbreviation;
    double number;
    struct Node *next;
};
void insert(char abbreviation, double number, struct Node *head) {
struct Node *current = head;
while(current->next != NULL)
{
    current = current->next;
}

struct Node *ptr = (struct Node*)malloc(sizeof(struct Node));
ptr->abbreviation = abbreviation;
ptr->number = number;
if(head->next==NULL)
{
    head=current=ptr;
}
else
{
    current->next = ptr;
}
return;
}

int main(int argc, char* argv[]) 
{
struct Node *head = (struct Node*)malloc(sizeof(struct Node));
insert('n',456,head);
printf("%s\n", head->abbreviation);
}
于 2013-03-21T04:49:14.670 回答