C中的值返回null,不确定原因

时间:2013-03-21 03:57:18

标签: c

为什么print语句返回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);
}

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

答案 2 :(得分:0)

要在insert()中致电main()之前添加到UncleO's answer,请将head->abbreviationhead->number设置为所需的值,并将head->next初始化为{{1}} NULL。

答案 3 :(得分: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);
}

答案 4 :(得分: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);
}