Reputation: 29
Here is the code of my tutorial
#include<iostream>
using namespace std;
int main()
{
int arr[5] = {8,2,9,4,5},a,b,*ptr;
int c = 5;
ptr = arr;
a = *ptr + 10;
ptr = &c;
ptr += 2;
cout<<*(ptr+1);
}
I'm a little confused why the output is 9. When ptr
is pointing to c
, which is valued 5, how can the pointer be incremented +2 since c
is not an array?
Upvotes: 0
Views: 267
Reputation: 2369
I think you are missing the * in ptr
#include<iostream>
using namespace std;
int main()
{
int arr[5] = {8,2,9,4,5},a,b,*ptr;
int c = 5;
ptr = arr;
a = *ptr + 10;
ptr = &c;
(*ptr) += 2;
cout<<*(ptr+1);
}
It will print 8, But your program undefined behavior due to this line
ptr += 2;
Upvotes: 0
Reputation: 104464
Undefined behavior
Let's break it down:
int arr[5] = {8,2,9,4,5},a,b,*ptr;
int c = 5;
ptr = arr; // ptr = address of arr[0]
a = *ptr + 10; // a = (arr[0] + 10) = (8 + 10) = 18
ptr = &c; // ptr = address of c
ptr += 2; // UNDEFINED BEHAVIOR, c is not an array
cout<<*(ptr+1); // COULD PRINT ANYTHING
Not that we've established undefined behavior, the language lawyers can't sue me to explain what might be happening:
The variables of main
are possibly piled onto the stack as follows. It's convenient that the elements on the stack are integer for this simple example:
0x100 c
0x104 arr[0]
0x108 arr[1]
0x10C arr[2]
0x110 arr[3]
0x114 arr[4]
0x118 a
0x11C b
0x120 ptr // address of the variable ptr, not what ptr points to
Hence, ptr+2
is the same address as the arr[1] in the array, which holds a value of "2". And then then the additional (ptr+1)
expression is the address of arr[2], which holds the value 9.
But that's because you are getting lucky. Any other system or compiler could crash the program or make the lights dim in your house. Such is the nature of undefined behavior.
Upvotes: 2
Reputation: 600
Output of your program is not deterministic. ptr pointing to c has been incremented by 2. As ptr was not pointing to contiguous memory structure (Like array), it is not possible to determine what ptr is pointing at after increment. As it is int pointer, every increment will cause it to jump by sizeof(int). Derefrencing ptr after increment will try to read next sizeof(int) bytes as int. So you can get any garbage value.
Upvotes: 0
Reputation: 156
Well, the pointer is not
pointing to c
.
when you did ptr += 2;
the pointer got incremented from c
and is now pointing to a memory space having a garbage value.
When I ran the code I got 612602545
as output which clearly is a garbage value. The output you get will differ each time you run the code or from system to system.
Upvotes: 0