Fred
Fred

Reputation: 211

Printing sub strings from command line arguments, in C

Why doesn't this work.

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

When this works?

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

Upvotes: 0

Views: 185

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126195

"%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.

Upvotes: 2

James McNellis
James McNellis

Reputation: 355019

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);

Upvotes: 6

Related Questions