繁体   English   中英

在Linux Mint上编译C程序时如何解决异常错误?

[英]How to fix unusual error while compiling c program on linux mint?

我写了一个C程序。 它可以在Windows 7上的DevC上编译并正常工作。但是,当我在Linux Mint上编译(使用'gcc main.c'命令)时,它不会编译并给出错误。 在Windows 7上编译时不会显示这些错误。因此,在Linux上也必定没有错! 如何通过gcc在Linux上编译它?

C代码:

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

int main(int argc, char *argv[])
{
   char command[100];

   printf("Enter the command:");
   scanf("%[^\t\n]", &command);
   printf("%s\n", command);
   strchr(command, '&');

   printf("%i", strchr(command, '&'));

   system("PAUSE"); 

   return 0;
}

错误:

mint@mint ~ $ gcc ass1/main.c
ass1/main.c: In function 'main':
ass1/main.c:8:5: warning: format '%[^   
' expects argument of type 'char *', but argument 2 has type 'char (*)[100]' [-Wformat]
ass1/main.c:11:3: warning: incompatible implicit declaration of built-in function 'strchr' [enabled by default]
ass1/main.c:13:5: warning: format '%i' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat]

在Windows 7上编译时不会显示这些错误。因此,在Linux上也必定没有错!

这是一个错误的结论。 在这种情况下,Windows上的编译器比gcc宽容得多。

gcc会警告您有关您的错误/错误,

scanf("%[^\t\n]", &command);

传递的地址command ,你应该传递的第一个字节的地址command ,或者作为command与自动阵列到指针的转换,或明确地作为&command[0]

您可以strchr未声明strchr情况下使用strchr ,这是C语言的非古代版本中的错误,但之前是允许的,其中use隐式声明了函数返回int 但是strchr返回char*

在您的printf调用中,您使用了错误的格式%i

gcc在这里是完全正确的。

请注意,这些是警告 ,(不幸的是)不是错误

这些不是错误,而是警告。 您的代码应该仍已编译。

第一个警告是因为您要将&command传递给类型为char (*)[100] scanf ,指定者%s期望使用char *类型的参数。 您只需要做的就是将command传递给scanf (不带& ),因为当传递给函数时, char数组将衰减为char*

您可能会发现代码仍然可以使用,并且command&command都引用相同的地址( printf("%p %p", command, &command); )。


第二个警告是由于您忘记包含声明了strchr <string.h>strchr 由于编译器找不到该声明,因此它隐式生成一个声明,该声明与实际的声明不匹配。


最后, strchr返回char* ,并且指定符%i用于int 如果要使用printf打印出地址,请使用%p指定符。


您还应该避免使用system("PAUSE"); (在Linux上不起作用),然后将其替换为等待用户输入的函数。

集成了先前的答案,这些代码将在Linux上编译并可以运行:

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // use this header to include strchr(command, '&');

int main(int argc, char *argv[])
{
   char command[100];

   printf("Enter the command:");
   scanf("%s", command);
   printf("%s\n", command);
   strchr(command, '&');

   printf("%p", strchr(command, '&')); 
   /* strchr(command, '&') returns a pointer so you need to tell printf you are printing one. */

   system("PAUSE"); 

   return 0;
}

输出:

oz@Linux:~$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:12:4: warning: statement with no effect [-Wunused-value]
oz@Linux:~$ ./a.out 
Enter the command:doSomething
doSomething
sh: 1: PAUSE: not found

代替

  system("PAUSE");

使用:printf(“按'Enter'继续:...”); while(getchar()!='\\ n'){
i = 1; } getchar(); 返回0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM