Printf

Hello I've got this code:

1
2
char a[] = "ABC";
    printf("%c", a);


It prints some weird char but when I use
printf("%s", a);

It prints the char array normally , why is that? why does a refer to the entire array rather than the first element like char *p = a; this refers to the first element of the array i suppose why isnt it the same?
Last edited on
Firstly, this is C, not c++. Incase you didnt know.

To answer your question -

What it prints out depends on what format string you use.

In the second case, printf("%s", a); -- %s prints out a string of characters, which in this case is ABC.

%c prints out a single character.

printf("%c", 'c'); // this simply prints out c
1
2
3
printf("%c", 65); // this prints out "A" becasue on the Ascii table 65 is A - http://www.asciitable.com/

// Read about how printf works - http://www.cplusplus.com/reference/cstdio/printf/ 


But printf("%c", a);
prints a weird ascii char that isn't any of the array's elements
A pointer to a char is not a char.
a is the address in memory of an array of characters. When you try to print a as a character, you end up taking the lower order byte of the address and treating that as a character. If a happens to be at an address in which the lower order byte is meaningful as a character, that's what you'll get. If not, you'll get garbage.
so change it to
printf("%c", a[0]); //or any other desired location.
Topic archived. No new replies allowed.