0

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!

2
Contributors
5
Replies
47
Views
3 Years
Discussion Span
Last Post by glao
0

Ok! I didn't know that,thanks!

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

0

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++;
 }

Edited by Ancient Dragon

0

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

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.