c - 在函数中使用 strcpy

标签 c pointers gcc gcc-warning strcpy

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

这是我写的程序,它基本上做的是,它将创建从用户那里获取结构值的链表。

当我从函数运行这个程序时,我得到了 2 个类似的警告

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

我不明白为什么要将 const 值传递给函数。

这个程序还有一个问题。在我输入第一个节点的信息后程序停止工作。

我在 windows 平台上使用 gcc 编译器。 请帮帮我。 谢谢...

最佳答案

问题不在于此。问题是您将 *first*second 作为 strcpy() 的第二个参数传递给 chars 而不是 char 指针。您必须简单地传递 firstsecond,即指针本身。

另请do not cast the return value of malloc.

关于c - 在函数中使用 strcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12549952/

相关文章:

c++ - 将成员函数作为成员函数的参数传递

c++ - 创建一个结构数组但稍后定义大小?

c - 在 Autoconf 项目中强制执行严格的 C99

c - fork 过程中的确定性 malloc

c++ - C 和 C++ 中的静态变量

c - put() 输出附加 "time"字符串

c - C语言中一个字符替换为两个字符

c++ - 检查输入是否是正确的整数

c - C中指向数组赋值的指针

c++ - 链接使用不同版本的 GCC 构建的目标文件