Reputation: 1617
I am learning how to get arguments in C, however, when I run the code below with the following input, the first one becomes null.
Input: ./a.out a b c d e f g h i j k
Output: (null) b c d e f g h i j k
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 2, j = 0;
char *foo = argv[1];
char *bar[10];
while(j < 10 && i < argc)
{
bar[j++] = argv[i++];
}
bar[j] = NULL;
printf("%s ", foo);
for(j = 0; bar[j] != NULL; j++)
{
printf("%s ", bar[j]);
}
printf("\n");
return 0;
}
Upvotes: 1
Views: 266
Reputation: 181027
You're setting bar[10] to NULL at the end of the loop, but it only goes up to bar[9]. Since foo is allocated just after bar on the stack, bar[10]=NULL overwrites foo instead.
Upvotes: 4
Reputation: 183968
At the end of the loop you write NULL
to bar[10]
, but you have only allocated bar[0 - 9]
. That probably overwrites foo
.
Upvotes: 5