Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character pointers and integer pointers (++)

Tags:

c++

c

pointers

I have two pointers,

char *str1;
int *str2;

If I look at the size of both the pointers let’s assume

str1=4 bytes
str2=4 bytes

str1++ will increment by 1 byte, but if str2++ it will increment 4 bytes.

What is the concept behind this?

like image 913
Vijay Avatar asked Apr 09 '10 07:04

Vijay


2 Answers

Simple, in the provided scenario:

  • char is 1 byte long
  • int (in your platform) is 4 bytes long

The ++ operator increments the pointer by the size of the pointed type.

like image 84
jweyrich Avatar answered Sep 28 '22 09:09

jweyrich


When doing arithmetic on a pointer, it's always in terms of the objects pointed at, not in bytes.

So a pointer whose target object is e.g. four bytes, will increase it's actual numerical value by four when you add one.

This is much more usable, and makes far more sense than having all pointer arithmetic be in bytes.

like image 31
unwind Avatar answered Sep 28 '22 09:09

unwind