strcpy错误:在字符串常量之前预期')'

时间:2017-03-24 02:17:00

标签: c string ubuntu gcc strcpy

我正在尝试在Ubuntu中运行一个C程序(使用gcc编译器),由于某种原因它不允许我使用strcpy函数。在下面的第二行代码中:

char test[10];
strcpy(test, "Hello!");

char c[2] = "A";
strcpy(test, c);

我收到以下错误:

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)

我已经包含以下标题:

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

我尝试在新文件中使用strcpy而没有额外的错误。我也尝试过使用:

memset(test, '\0', sizeof(test));

在使用strcpy之前,无济于事。

我已经检查了所有的左括号,并且它们都有相应的结束)。另外,当我注释掉strcpy行时,错误就会消失。

非常感谢任何见解。

1 个答案:

答案 0 :(得分:3)

char test[10];
strcpy(test, "Hello!");

char c[2] = "A";
strcpy(test, c);

如果我理解正确,那么你在文件范围那些行。行strcpy(test, "Hello!");语句,语句仅在函数体内合法。因为编译器当时并不期望语句,所以它试图将该行解释为声明。

以下内容基于您的代码是合法的(尽管它没有做任何有用的事情):

#include <string.h>
int main(void) {
    char test[10];
    strcpy(test, "Hello!");

    char c[2] = "A";
    strcpy(test, c);
}