following code:
int main(){
int a;
int b;
int c=0;
int *p;
p=&a;
*p = 10;
*(p 1) = 20;
*(p 2) = 30;
cout << a << " " << b << " " << c << endl;
return 0;
}
gives the output:
10 30 20
explanation ? if c is not initialized (int a,b,c;) results are expected: 10 20 30
CodePudding user response:
That’s outright undefined behavior. Pointer arithmetic is only allowed inside single array (not even between struct members, although some compilers might tolerate the latter). The local variables don’t form an array. They may have arbitrary locations in memory.
CodePudding user response:
You've made an assumption that *(p 1) is b. There's no reason that will always be the case. How a compiler assigns memory addresses for variables is completely undefined, and will vary hugely based on many different factors (in your example, initialising a variable earlier changes it. The other big thing that would change it would be compiler optimizations). You really shouldn't be relying on relative memory locations.
CodePudding user response:
Pointer (p 1) doesn't point to integer variable b and pointer (p 2) doesn't point to variable c. So when you cout those variable you are getting vague values. Instead try using array because while initialising arrays compiler assign continuous memory for arrays. But when you declare variables continuous memory isn't assigned by compiler
Int a[3];
Int *p;
p = &a;
*p = 10;
*(p 1) = 20;
*(p 2) = 30;
cout<< a[0] <<a[1] <<a[2] ;