5

I'm trying to print the whole word instead of just the first letter. I could do it with a loop but I figured there was a better way. I was searching around and saw answers that they changed %S to %c but I'm already using %c since it's a character array.

char* words[] = {"my", "word", "list"};
printf("The word: %c",*words[2]);

Results:
The word: l

2 Answers 2

9

The issue is that you dereferenced twice. The [2] in *words[2] dereferences from words[] to "list" then the * dereferences a second time from "list" to 'l' Remove the * and voila.

char* words[] = {"my", "word", "list"};
printf("The word: %s", words[2]);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah I see, I was wondering about the dereferencing but I was getting random characters if I didn't before when I was using %S I might have read the lowercase as an upper case. Thank you that solved it.
4

You need to use %s, a format used specifically for null-terminated arrays of characters (i.e. C strings). You do not dereference the array's element when you pass it to printf, like this:

printf("The word: %s\n", words[2]);

1 Comment

I must have read the code wrong when I did my search I did have %S but as you can see I used uppercase. I was getting random characters which I figured it was displaying from the address which is why I double derefferenced it. Removed that and changed it to s now everything works. Thanks.

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.