0

Why doesn't this work.

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

When this works?

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

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Thank you, I just saw that you added some info to your comment.
2

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.