Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print char pointer char array with printf?

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
like image 439
krizzo Avatar asked Dec 15 '22 17:12

krizzo


2 Answers

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]);
like image 182
Mel Nicholson Avatar answered Dec 22 '22 00:12

Mel Nicholson


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]);
like image 29
Sergey Kalinichenko Avatar answered Dec 22 '22 01:12

Sergey Kalinichenko