top button
Flag Notify
Site Registration

When pointer contains only address, what is the point of declaring pointer of different type?

+4 votes
535 views

What is the point of declaring Pointer of different types (eg. integer,float,char) as we all know pointer takes 4 bytes of space regardless which type of pointer it is and only contains address?

posted Mar 26, 2016 by Shahsikant Dwivedi

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Pointer is not just address but address and type. So that we can say what type of value it can contain for the ease of programming, void pointer was an extension to it.

Hope I understood your query correctly.

2 Answers

+1 vote
 
Best answer

although pointer holds address but for eg int *p; here data type int means that this pointer variable p will point to an integer variable.
since,data type is an interpretation of bits..so when we are dereferencing the pointer to get the value stored at the location which is in p,this int data type will tell the compiler to interpret the value stored as integer type .
in c++ ,it would give an error if we mismatch the datatypes but in c it will run but will give a warning message.

answer Mar 28, 2016 by Aman Mehrotra
0 votes

This is because each pointer has its scalar value. If a pointer is declared as void, it can't be de-referenced.
I would like to share a piece of code for the same:

#include <stdio.h>
int main ()
{
int a[5] = { 1, 2, 3, 4, 5};
void *ptr = a;
printf ("%d", *ptr);
return 0;
}

When I compile above code, compiler throws "error: invalid use of void expression".

But you change type of ptr from void to int, it works.
#include <stdio.h>
int main ()
{
int a[5] = { 1, 2, 3, 4, 5};
int *ptr = a;
printf ("%d", *ptr);
return 0;
}

answer Mar 26, 2016 by Vikram Singh
vikram thank you for your answer but i am not talking about void pointer..suppose this scenario:-  i am declaring and integer pointer and character pointer..but pointer will take space of 4 bytes and will contain only the address..so why is it that for integer type value we take integer type pointer and for character type we take character type pointer and for rest we do the same.
...