Okay so, i need to write a C program which handles and compares command line arguments. For example, lets say the program is called test.c. I execute it like that : ./test load something store one two load store ...etc. What i mean by that is when there is a "load" command it will parse the argc+1 and do something with it and when there is a "store" command it's goind to be doing something else and parsing both argc+1 and argc+2. Heres is my approach so far :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Tooks {
char s1[50];
char s2[50];
char s3[50];
} Test; /*use this struct to compare the command line arguments in
which in am interested at every time. */
int main (int argc, char *argv){
int num = argc;
int y,i;
char args[num][50]; /*use this num-places array with each string
containing 50 chars. I did that because if i try directly to
strcpy( test.s1, argv[i]) i would get a seg fault. */
Test test;
strcpy( test.s1, "null");
strcpy( test.s2, "null");
strcpy( test.s3, "null");
for (y=0; y<num; y++){
strcpy(args[y], "null");
}//"initializing" the array as null
for (i=1; i<num;){
//copy the 3 command line arguments.
strcpy( test.s1, args[i]);
strcpy( test.s2, args[i+1]);
strcpy( test.s3, args[i+2]);
printf("s1 %s, s2 %s, s3 %s, num %d\n", test.s1, test.s2, test.s3, num);//Just a test print
if (strcmp(test.s1, "store")==0 && strcmp(test.s2, "null") != 0 && strcmp(test.s3, "null") != 0){
printf("%s\n, %s\n", test.s2, test.s3);
i=i+3;
}
else if (strcmp(test.s1, "load")==0 && strcmp(test.s2, "null") != 0){
printf("%s\n", test.s2);
i=i+2;
}
else {
printf("nothing\n");
printf("s1 %s, s2 %s, s3 %s\n", test.s1, test.s2, test.s3);
i++;
}
}
printf("end %d\n", argc);
return 0;
}
And here is the output:
s1 null, s2 null, s3 null, num 6
nothing
s1 null, s2 null, s3 null
s1 null, s2 null, s3 null, num 6
nothing
s1 null, s2 null, s3 null
s1 null, s2 null, s3 null, num 6
nothing
s1 null, s2 null, s3 null
s1 null, s2 null, s3 �, num 6
nothing
s1 null, s2 null, s3 �
s1 null, s2 �, s3 , num 6
nothing
s1 null, s2 �, s3
end 6
for the command ./test load something store one two
It seems that the command line arguments are not passing neither to the struct nor to the array. Any ideas? :)
argv, so there is no way you will get the command line arguments.argv[0]refers to the executable name itself. You are not really passing arguments into the app itselfi. Within that loop, some of the threestrcpystatements will break theargsarray.args[i+2]in the final iteration wheni == num-1will beargs[num+1]which clearly exceeds the array bounds.