【问题标题】:usage of strcpy in functionsstrcpy 在函数中的使用
【发布时间】:2012-09-15 00:32:43
【问题描述】:
#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 编译器。 请帮帮我。 谢谢...

【问题讨论】:

  • 您的代码不做任何长度检查。如果有人在自己的名字中输入超过 19 个字符,就会发生坏事。

标签: c pointers gcc gcc-warning strcpy


【解决方案1】:

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

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

【讨论】:

  • @user1632141 正是,这是警告?
  • ANSI C++ 禁止在初始化时从 `void *' 进行隐式转换
  • 您将此问题标记为c,而不是c++。如果它实际上是一个C++ 程序,那么你会得到错误的建议。
  • @user1632141 哇...这不是我的错!您将此问题标记为 C,此代码似乎是 C,......但您将其编译/视为 C++。不要那样做。
【解决方案2】:

这里:

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

firstsecond 是指针(指向char)。没有理由使用 * 取消引用它们并提取字符。 strcpy() 将指针作为其参数。 firstsecondstrcpy() 有好处。

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2021-05-11
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2020-08-16
    • 2015-01-27
    • 1970-01-01
    相关资源
    最近更新 更多