簡體   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