2013-03-21 75 views
0

为什么print语句返回null?C中的值返回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); 
} 
+2

尝试使用'%C',而不是'%s' – nabroyan 2013-03-21 03:59:15

+2

如果你的问题是关于C,请不要加'[C++]'标签。 – 2013-03-21 03:59:58

+3

而且,由于C++代码消失了,不投中C. – 2013-03-21 04:00:32

回答

2

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

3

您正在创建头戴式> next指向一个节点,然后插入值出现。您从不在头节点中设置任何值。

0

为了增加UncleO's answer,在你main()调用insert()之前,设置head->abbreviationhead->number到所需的值并初始化head->next为NULL。

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); 
} 
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); 
} 
相关问题