I am using strcmp in following ways
- Passing char[] array names
-
Passing pointers to string literals
but, the second result in seg fault. even though i have confirmed that pointers point to correct string literals, i am confused as to why i am getting seg fault..
Here is the code:-#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char const *args[]) { char firstName[strlen(*++args)]; strcpy(firstName, *args); char lastName[strlen(*++args)]; strcpy(lastName, *args); printf("%s\t%s\n", firstName, lastName); printf("%d\n", strcmp(firstName, lastName));// this works printf("%d\n", strcmp(*(--args),*(++args)));//this gives me a seg fault return EXIT_SUCCESS; }
I am saving it as str.c and when i compile it, first i get following warning:
[Neutron@Discovery examples]$ gcc -Wall str.c -o str
str.c: In function ‘main’:
str.c:15: warning: operation on ‘args’ may be undefined
finally running it, gives a seg fault as shown below
[Neutron@Discovery examples]$ ./str Jimmy Neutron
Jimmy Neutron
-4
Segmentation fault (core dumped)
Don’t use
--and++when you pass the same variable to the same function twice as two different parameters.Instead of
printf("%d\n", strcmp(*(--args),*(++args)));do
Still not really readable (better use indexes and check against
argcfor validity), but at least you don’t change the value and evaluate multiple times it at the same sequence point.