Gokul
Gokul

Reputation: 1226

What is the main difference between integer pointer and character pointer?

Consider this code:

int a=100;
int *p1=&a,**p2=&p1;
char *p3=&a,**p4=&p3; //Here *p1,*p3,**p2,**p4 all return 100
p4=&p1;
p2=&p3;

*p1, *p3, **p2 and **p4 all return 100.

I want to know the significance of specifying a pointer as integer and character.

Upvotes: 1

Views: 16562

Answers (3)

Nikos C.
Nikos C.

Reputation: 51920

The type of a pointer determines what assumption the compiler makes about the size and layout of the pointed-to data. In your example:

char *p3=&a

&a is assumed to hold a char value, and thus be one byte long. This is of course not true, since an int is at least two bytes long (and is usually four bytes long). Now the reason why you still get the value 100 out of it, is because you're most probably running this code on an Intel-compatible CPU, where the bytes are stored in little-endian format. In this format, the least significant bytes are stored first, not last. A four-byte integer with the value 100 is stored like this (hexadecimal notation):

0x64 0x00 0x00 0x00

p3 points at the first byte of this sequence. Therefore, the memory pointed to by p3 contains a byte with the value 100. If you were to use a value with this layout:

0x00 0x64 0x00 0x00

Which is 25600:

int a=25600;

then the value you'll get for *p3 is 0, since only the first byte is taken into account.

In addition to that, the value of *(p3+1) is 100, since incrementing a char pointer by one will result in a pointer to the next byte (which has the value 100). This is different from *(p1+1), which would give you a memory address that that lies four bytes after p1.

Upvotes: 1

markmb
markmb

Reputation: 892

As pointer, there's basically no difference. The difference is when dereferencing the pointers and assigning values.

Type char is a byte wide type. This means, it can store 8 bits of information. So type char can store numbers from -127 to 126.

Type int is a 4-byte wide type, so it can store 32 bits of information. You can apply the same concept, to see the maximum and minimum values you can store.

You can learn more here

Upvotes: 3

Algorithmist
Algorithmist

Reputation: 6695

Another Difference lies when you increment the pointer, each pointer increment by its corresponding element type.

char *str1;
int *str2;
if you will look at the size of both the pointers lets assume
str1=4 bytes,str2=4 bytes

str1++ will increment by 1 byte but str2++ will increment 4 byte.
Reason: The ++ operator increments the pointer by the size of the pointed type.

Upvotes: 5

Related Questions