我正在尝试在 Ubuntu 中运行一个 C 程序(使用 gcc 编译器),但由于某种原因它不允许我使用 strcpy 函数。在下面的第二行代码中:
char test[10];
strcpy(test, "Hello!");
char c[2] = "A";
strcpy(test, c);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
testChTh.c:56:14: error: expected ‘)’ before string constant
strcpy(test, "Hello!");
^
testChTh.c:59:1: warning: data definition has no type or storage class
strcpy(test, c);
^
testChTh.c:59:1: warning: type defaults to ‘int’ in declaration of ‘strcpy’ [-Wimplicit-int]
testChTh.c:59:1: warning: parameter names (without types) in function declaration
testChTh.c:59:1: error: conflicting types for ‘strcpy’
In file included from testChTh.c:3:0:
/usr/include/string.h:125:14: note: previous declaration of ‘strcpy’ was here
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
Run Code Online (Sandbox Code Playgroud)
我已经包含了以下标题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Run Code Online (Sandbox Code Playgroud)
我试过在一个没有额外的新文件中使用 strcpy ,但出现了同样的错误。我也试过使用:
memset(test, '\0', sizeof(test));
Run Code Online (Sandbox Code Playgroud)
在使用 strcpy 之前,无济于事。
我检查了我所有的左括号,它们都有一个相应的结尾)。另外,当我注释掉 strcpy 行时,错误消失了。
任何见解都非常感谢。
char test[10];
strcpy(test, "Hello!");
char c[2] = "A";
strcpy(test, c);
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,您在文件 scope 中有这些行。该行strcpy(test, "Hello!");是一个statement,并且语句仅在函数体内才是合法的。因为编译器在那个时候并不期待一个语句,它试图将该行解释为一个声明。
根据您的代码,以下内容是合法的(尽管它没有任何用处):
#include <string.h>
int main(void) {
char test[10];
strcpy(test, "Hello!");
char c[2] = "A";
strcpy(test, c);
}
Run Code Online (Sandbox Code Playgroud)