Search code examples
cpointersgccgcc-warningstrcpy

usage of strcpy in functions


#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;
  } 

This is the program I have written,what it basically does is,it will create linked list taking the values of the structures from the users.

I got 2 similar warnings when i run this program from the function

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

I don't understand why it is passing const value to the function.

And I have one more problem with this program.The program stops working after I enter the information for first node.

I am using gcc compiler on windows platform. Please help me out. Thanks...


Solution

  • The problem is not that. The problem is that you're passing *first and *second as the second argument for strcpy() which are chars and not char pointers. You must simply pass first and second, the pointers themselves.

    Also, please do not cast the return value of malloc.