Why do I get a from the console with the following code?
char array1[] = "Hello World";
char ch = array1;
printf(" %s" , ch);
(We are instructed not to do this with a pointer)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because you need to make ch a pointer to a character. The compiler should have given you a warning that you were assigning a character pointer to a character variable, and it should have warned you that you were trying to
printf("%s")on a non-character-pointer variable — if it didn’t, you should turn up your compiler’s warning level!Just adding that one little, easily-forgotten star makes it work correctly:
I also took the liberty of adding a newline on the end of your string and putting it in a proper
mainfunction, for the sake of completeness.I just noticed that you said you “aren’t allowed to do this with pointers” — pretty much the only other way to do it is to print out character-by-character until you hit a null terminator:
output:
A more robust approach would be to also put a limit on how many characters you will print out, but just checking for
\0is probably fine enough for what seems to be a homework assignment.