This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

C printf error



this code keep giving me black question mark error, I am trying to implement the code something is wrong, please help.










#include <stdint.h> #include <stdbool.h> #include <stdio.h> int main() { char a = 'b'; printf("%c",(char *)(&a)); return 0; }

  • A pointer to a char is not a char. Perhaps you have mistaken the printf() interface with scanf() ?

  • Thanks for your reply, I find out that what I passed to the printf() is only a pointer address, when I add a * to the pointer, it works and print out the alphabet b, but I am a little confused, I check the printf source code,

    int printf ( const char * format, ... );

    it is a char pointer, which to my understand, it is only an address, so that is why I only pass a pointer instead of a *pointer, can anyone help me to understand this ?

    Thanks

    Shan
  • %c - prints a character
    %s - prints a string

    characters (char) are one of the smallest integer types (along with signed char and unsigned char)
    strings are arrays of chars

    So %s expects the start of the array of chars (with a 0 indicating the end of the string) and %c expects the value. The start of the array is the address of the first array member..

    Also *&a is the same as a.

    Consult a C tutorial book for more of an explanation.

    Robert
  • Hi, Robert, Thanks for your reply

    char a = 'b';
    printf((char *)(&a));

    compare with

    int printf ( const char * format, ... );

    the printf is asking for a char pointer to print out the value where the pointer pointed to. The compiler give me wrong value instead of b.

    can you help me with this? I just want to understand the definition itself, and find out where is my misunderstand of this.

    Thanks

    Shan
  • A char is not a string, neither is a pointer to a char (even though they share the same type).

    You need to find and read a tutorial introduction to C. There are several books and probably many websites now that provide varying quality tutorials. I don't have the time to teach the language to you and this is not the proper forum for that in any case. This understanding is pretty fundamental to both C and C++.

    Maybe someone has reference to a good up to date introductory tutorial?

    Robert
  • Thanks, I will.

    Shan