【问题标题】:Unable to use the 'strcpy()' function. Generating error even after using #include <string.h>无法使用“strcpy()”函数。即使在使用 #include <string.h> 之后也会产生错误
【发布时间】:2014-07-22 08:05:37
【问题描述】:

Practice.c

#include <stdio.h>
#include <string.h>

int main(void)
{
  char srce[]="abcd fghi jklmn";
  char dest[20];

  strcpy(dest,sizeof(srce),srce);

  printf("\n%s",dest);

  return 0;
}

在编译时我明白了:

Practice.c: In function 'main':
Practice.c:9:3: warning: passing argument 2 of 'strcpy' makes pointer from integer
without a cast [enabled by default]
   strcpy(dest,sizeof(srce),srce);
   ^
In file included from Practice.c:2:0:
c:\mingw\include\string.h:57:39: note: expected 'const char *' but argument is of
type 'unsigned int'
 _CRTIMP char* __cdecl __MINGW_NOTHROW strcpy (char*, const char*);
                                       ^
Practice.c:9:3: error: too many arguments to function 'strcpy'
   strcpy(dest,sizeof(srce),srce);
   ^

是我strcpy()的语法写错了,还是我的代码不正确?

链接到书籍和网页,以研究数组、字符串、指针和结构

目前我正在使用Apress: Beginning C 5th Edition

【问题讨论】:

  • 错误信息很清楚,参数不匹配,仔细阅读。阅读strcpystrncpy的手册。
  • @VSP 我在答案中添加了教程链接。

标签: c arrays string gcc


【解决方案1】:

strcpy 只需要 2 个参数。 源字符串指针和目标字符串指针。 您可以删除第二个参数“sizeof(srce)”

【讨论】:

  • 但这是我目前使用的书中的语法。
  • 如果是这样,请摆脱那本书
  • @Quentin 能否提供我问题最后 3 行的答案。拜托,非常感谢您的帮助。
  • @Matt McNaabb 能否提供我问题最后 3 行的答案。拜托,非常感谢您的帮助。
  • 是的,你错了 strcpy 的语法错误。您的代码不正确。 “Gaurav”已经解释了这一点。您问题的最后两行不是问题。
【解决方案2】:

函数的正确用法是:

char * strcpy ( char * destination, const char * source );

您可以查看this link了解更多信息。

编辑:

您可以从this page 学习 C 教程。

【讨论】:

    【解决方案3】:

    概要检查strcpystrncpy之间的区别

    char *strcpy(char *dest, const char *src);
    char *strncpy(char *dest, const char *src, size_t n);

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
      char srce[]="abcd fghi jklmn";
      char dest[20];
    
      strncpy(dest, srce, strlen(srce));
    
      printf("\n%s",dest);
    
      return 0;
    }
    

    【讨论】:

    • 那行不通。 strlen(srce) 只是15,所以'\0' 没有在dest 的末尾。所以printf 会溢出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多