Search code examples
carrayspointersimplicit-conversionc-strings

Should this pointer be acting this way? Basic C


From my understanding, pName should be a pointer with the value of the memory location of the char name.
Which means, when I dereference the pointer variable pName in the second printf statement, it should just print the string of characters "Cameron". BUT IT DOESNT! Could someone help this noob out :)?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char name[] = "Cameron";
    char * pName = &name;

    printf("Printing string of characters: %s\n", name);
    printf("Dereferencing pointer and printing string: %s\n", *pName);
    printf("Printing pointer: %p\n", &name);
    printf("Printing pointer another way %p\n", pName);

    return 0;
}

Solution

  • pName is a char*, a pointer to char. So when you do *pName, you get a char which is not a string that you can print with %s.

    Instead of

    char *pName = &name;
    

    you need:

    char (*pName)[] = &name; // a pointer to an array of chars.
    

    Now your dereference/printf will work as expected.

    Also the format %p requires it argument to be of type void*. So you need to cast the arguments to void* in printf calls.

    See 7.21.6.1 The fprintf function:

    p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.