I have the following piece of code:
#include <stdio.h>
int main ( int argc, char *argv[] )
{
int M, N;
M = 1;
N = 1;
curr = 1;
if ( argv[1][0] == '-' )
{
curr = 2;
char *a = argv[1][1];
char *b = argv[1][3];
M = atoi(a);
N = atoi(b);
}
printf("%d\n%d", M, N);
}
So, I pass this program something like this:
a.out -1,2
and instead of getting expected output
1
2
I get a segmentation fault. What gives?
That compiles?!
char argv*[] is an array of char pointers.
char *a = argv[1][1]
will
char *
.So now you are assigning a char to a char pointer (which should be a compile error).
I can only assume you meant to say char *a = &argv[1][1]
. Btw, const-correctness would be nice too, so const char *a = &argv[1][1]
.
Btw, your code is still very unsafe - you don't even check the size of the string. Imagine what &argv[1][3]
does if your string only has two characters.