I have written a C program. It compiles and works fine on DevC on Windows 7.
But when I compile it on Linux mint (using ‘gcc main.c’ command) it does not compile and give errors. These errors are not shown while compiling on Windows 7. So nothing must be wrong on Linux as well! How to compile it on Linux through gcc?
C Code:
#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;
}
Errors:
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]
Those aren’t errors, they’re warnings. Your code should have still compiled.
The first warnings is because you’re passing
&commandtoscanf, which is of typechar (*)[100], and the specifier%sexpects an argument of typechar *. All you simply need to do is passcommandtoscanf(without the&), since achararray will decay into achar*when passed to a function.You’ll probably find that the code still works, with
commandand&commandboth referring to the same address (printf("%p %p", command, &command);).The second warning is due to you forgetting to include
<string.h>, which declaresstrchr. Since the compiler can’t find the declaration, it implicitly generates one, which doesn’t turn out to match the real one.Lastly,
strchrreturns achar*, and the specifier%iis intended to be used forints. If you want to print out an address usingprintf, use the%pspecifier.You should also probably avoid
system("PAUSE");(which won’t work on Linux), and replace it with a function that waits for user input.