2013-03-21 74 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); 
} 
相關問題