Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the data type needed in pointer declarations?

Tags:

c++

c

pointers

As far as I know about data types in C/C++, while declaring a variable, we need to declare its data type, which tells the compiler to reserve the number of bytes in the memory accordingly.

But in the case of pointers, we know that their size is constant (eg. 2 bytes in "Turbo Compiler"), irrespective of the data type of the variable it is pointing to, because the pointer is storing a memory address as an unsigned integer.

My question is, if the pointers are always a constant size in bytes, then what is the need of mentioning the data type while declaring them? Is my understanding about pointers wrong?

like image 779
Chandra Sekhar Avatar asked Mar 21 '12 10:03

Chandra Sekhar


People also ask

Why do we need data type for a pointer?

The data type of pointer is needed when dereferencing the pointer so it knows how much data it should read. For example, dereferencing a char pointer should read the next byte from the address it is pointing to, while an integer pointer should read 4 bytes.

What is pointer type declaration?

A pointer declaration names a pointer variable and specifies the type of the object to which the variable points. A variable declared as a pointer holds a memory address.

What type of data is a pointer?

A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address. Pointers are essential for dynamic memory allocation.

Why do pointers have to of same datatype as that of the variables they are pointing to?

Why is it important for a pointer to have the same data type as of the variable it is pointing to? Using the increasement operator operator (++) moves the pointer to the next element. If the pointer type is unknown (void) then the compiler doesn't​ know the size, so doesn't know how many bytes to move.


1 Answers

The data type is needed when dereferencing the pointer so it knows how much data it should read. For example dereferencing a char pointer should read the next byte from the address it is pointing to while an int pointer should read 2 bytes.

like image 108
glindste Avatar answered Oct 12 '22 22:10

glindste