Hello , I have the following code :

int a = 2;
int *ptr = &a;
int *second = &a + 1;

printf("\n ptr = %p\n", ptr);
printf("\n second = %p\n", second);

which just prints the address of pointers and the address of second is 4bytes next the ptr.
Output:

ptr = 0x7fffc26238b4

second = 0x7fffc26238b8

Ok until here.

If I add to the above code :

 int *Newptr;
 Newptr = second +1;

 printf("\n New ptr = %p\n", Newptr);

then I am getting:

 ptr = 0x7fff4086945c

 second = 0x7fff40869460

 New ptr = 0x7fff40869464

The ptr now has different address now.The second isn't being increased by 4 bytes from the ptr.Why?

Also, when do we use :

Newptr = second +1;

When we want the Newptr to point to next memory address from second?But why?

Thanks!

Recommended Answers

All 5 Replies

The second isn't being increased by 4 bytes from the ptr.

Yes it is. 945c + 4 = 9460 (5c+1=5d, 5d+1=5e, 5e+1=5f, 5f+1=60)

Ok! I didn't know that,thanks!

And in which situations we use this kind of approach?Can you tell me?

One situation is when accessing arrays of integers. This is just a very simple example.

int array[10] = {1,2,3,4,5,6,7,8,9,10};

int* p = array;
int i;
for(i = 0; i < 10; i++)
{
   *p += i;
   p++;
 }

Ok with that.
What about ptr = anotherptr +1.

This points to next memory address.So it points for example to anotherptr[1]?

Ok , I got it.This is it.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.