2012-09-23 44 views
0
#include<stdio.h> 
#include<stdlib.h> 
#include<ctype.h> 
#include<string.h> 

struct person *create_node(char *, char *,int); 
void addnode(char *,char *,int,struct person *); 


struct person 
{ 
    char fname[20]; 
    char sname[20]; 
    int pno; 
    struct person *next,*prev; 
}; 

struct person *create_node(char *first,char *second,int mob) 
{ 
    struct person *pnode=(struct person *)malloc(sizeof(struct person)); 
    strcpy(pnode->fname,*first); 
    strcpy(pnode->sname,*second); 
    pnode->pno=mob; 
    pnode->next=pnode->prev=NULL; 

    return pnode; 

} 

void addnode(char *first,char *second,int mob,struct person *pnode) 
{ 
    while(pnode->next!=NULL) 
    { 
     pnode=pnode->next; 
    } 
    pnode->next=create_node(first,second,mob); 
    pnode->next->prev=pnode; 

} 

int main() 
{ 
    struct person *root=NULL; 
    char choice='y'; 
    char first[20]; 
    char second[20]; 
    int mob; 

    while(tolower(choice)=='y') 
    { 
     printf("enter the first name:"); 
    scanf("%s",first); 

    printf("enter the second name:"); 
    scanf("%s",second); 

    printf("enter the mobile no:"); 
    scanf("%d",&mob); 

    if(root==NULL) 
    root=create_node(first,second,mob); 
    else 
    addnode(first,second,mob,root); 
    printf("enter the option to continue or end(y or n):"); 
    scanf("%c",&choice); 
    fflush(stdin); 
    } 

    return 0; 
    } 

這是我寫的程序,它基本上做的是,它將創建鏈接列表,並從用戶中獲取結構的值。strcpy在函數中的用法

我得到了2個類似的警告當我從功能

struct person * create_node(char *, char *, int), 
    passing char to argument 2 of strcpy(char *, const char *) lacks a cast 

我不明白爲什麼它被傳遞const值的函數運行此程序。

而且我還有一個這個程序的問題。我輸入第一個節點的信息後程序停止工作。

我在windows平臺上使用gcc編譯器。 請幫我一把。 謝謝...

+3

你的代碼不會做任何長度檢查。如果有人輸入超過19個字符的名字,就會發生不好的事情。 – DCoder

+0

感謝您照顧那個...... – starkk92

回答

4

問題不在於此。問題是你通過*first*second作爲strcpy()的第二個參數,它們是char s,而不是char指針。你必須簡單地通過firstsecond,指針本身。

另外,請do not cast the return value of malloc.

+0

非常感謝...不知道我是如何錯過的: -/ – starkk92

+0

但它在使用鑄造時顯示警告 – starkk92

+0

@ user1632141準確地說,這是警告嗎? – 2012-09-23 05:47:50

2

這裏:

struct person *create_node(char *first,char *second,int mob) 
{ 
    // ... 
    strcpy(pnode->fname,*first); 
    strcpy(pnode->sname,*second); 
    // ... 
    return pnode; 
} 

firstsecond是指針(至char)。沒有理由將其解除引用*並提取字符。 strcpy()以指針爲參數。 firstsecond適合於strcpy()