简体   繁体   中英

How can I print something from a pointer?

I wrote this program to test something with pointer. The two words in the array will be swapped at the end.

int main() {

char * word2 [] = { "LAGER" , "GERALD" };

char * temp = NULL;

temp = word2[0];        

word2[0] = word2[1];    
word2[1] = temp;        

printf("%c \n" , *word2[1]);

return 0;

}

I now want to print the second word after they swapped but it only prints the first letter and not the whole word. How do I print the whole word?

This call of printf

printf("%c \n" , *word2[1]);

outputs the first character of the second element of the array that stores pointers to string literals.

That is as the expression word2[1] has the type char * due to the declaration of the array then the expression *word2[1] has the type char and the function printf using the conversion specifier %c outputs the character..

Instead write

printf("%s\n" , word2[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM