views:

81

answers:

2

Why doesn't this work.

printf("%s\n", argv[1][3]);

When this works?

printf("%c\n", argv[1][3]);
+6  A: 

Because the %s format specifier tells printf that the argument is a null-terminated string. You're giving printf a single character--the fourth character in the second element of the argv array.

If you want to print the substring from the fourth character to the end of the string, you can do that too, you just have to get a pointer to that character:

printf("%s\n", &argv[1][3]);

or, if you prefer:

printf("%s\n", argv[1] + 3);
James McNellis
But it is a null terminated string, I just want it to start from offset 3 and keep printing until null.How would I achieve the same thing then?
Fred
Thank you, I just saw that you added some info to your comment.
Fred
+2  A: 

"%s" in a foramt string expects a 'char *' argument, but you're passing it a 'char' so you get garbage (probably a crash). "%c" in a format string expects a 'char' argument, which is what you are giving it, so it works.

Chris Dodd
Less likely a crash than a compiler error. GCC (at least) can do type checking for format-string functions like `printf` and `scanf`.
Chris Lutz