Manuel Amador
Manuel Amador

Reputation: 119

understanding pointer logistics in printf statement

I'm learning pointers in C but I'm slightly confused with this example. What is the pointer logistic for the pointers in the three printf() statements below? What are these: *(char*)ptr, *(int*)ptr, (char*)ptr+2, exactly doing?

#include<stdio.h>
int main()
{
    void *ptr;
    char ch=74, *cp="CS107";
    int j=65;
    ptr=&ch;
    printf("%c\n", *(char*)ptr);
    ptr=&j;
    printf("%c\n", *(int*)ptr);
    ptr=cp;
    printf("%s\n", (char*)ptr+2);
    return 0;
}

Upvotes: 3

Views: 193

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

I believe you're already got your answer, but just to clarify a hidden point, let me add some more info to already existing answers.

  • printf("%c\n", *(char*)ptr);

    Cast the void pointer ptr to a char pointer, then de-reference to print the char value.

  • printf("%c\n", *(int*)ptr);

    Cast the void pointer ptr to an int pointer, then de-reference to print the char representation of that int value.

  • printf("%s\n", (char*)ptr+2);

    Here, the operator precedence comes into play. As the cast operator will take precedence over binary addition, first the ptr will be casted to char *, and then, the pointer arithmetic will come into effect, incrementing the pointer to point to the 3rd char element (0 based indexing, remember?).

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

  • *(char*)ptr : Treat the value of ptr as a pointer that pointing to char data, then read the char data pointed by ptr
  • *(int*)ptr : Treat the value of ptr as a pointer that pointing to int data, then read the int data pointed by ptr
  • (char*)ptr+2 : Treat the value of ptr as a pointer that pointing to char data, then calculate a pointer pointing to a char data which is 2 elements ahead from the element pointed by ptr

Upvotes: 1

Haris
Haris

Reputation: 12270

(char*)ptr is called casting. A pointer of one type(ptr) is cast to point to a variable of another type(char*).


In your example, ptr is a pointer of type void, and it is used at various places to point to different types of variables.

ptr=&ch; this makes it point to a variable of type char.

However, the pointer ptr itself is of type void only, so later in printf() statement, it has to be explicitly casted to type char* to make it work.

printf("%c\n", *(char*)ptr);
                ^^^^^^^

Then, it is dereferenced to access the element residing in that memory.

printf("%c\n", *(char*)ptr);
               ^

Same goes for other types which follows.

Upvotes: 1

Related Questions