Here’s what I have:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv)
{
while(*argv++ != 0)
{
printf("Argument!\n");
printf("%s %d\n",*argv,(int)strlen(*argv));
int i = 0;
while(*argv[i])
{
printf("char!\n");
printf("%c\n",*argv[i]);
i++;
}
printf("End of for loop\n");
}
return 0;
}
When I run ./a.out test, the output is:
Argument!
test 4
char!
t
Segmentation Fault
I’ve been staring at this for a few hours. Why won’t my program print each command line argument character by character?
I’m new to C, and the array-pointer duality, so I wouldn’t be surprised if that were the problem. Any help is appreciated!
First version
What you want is use argc:
The output is actually letter by letter as you needed:
Second version:
You can use the pointer notation for
jbut not forisince you don’t know the letter count of each argument. It could of course be achieved by usingstrlenwhich would lead under the hood to an iteration through the string to count the letter, which is not what you want to do. If you can do it in one iteration through the argument why do it in two?