0
Why i don't get what i want in line 11 ,23 ,27 in this code ?
5 odpowiedzi
+ 1
11: printf("%d\n", *q); // why not printing 67 .
Because in line 7, q = &a[0] + 3. The assignment is the same as q = &a[3], and 56 is in a[3]. (Notice 67 is in a[4]).
23: printf("%d\n", *p); // Why not printing 54 ?
Because in line 6, p is initialized to a (a.k.a. &a[0]). Then p is incremented once in line 13 to &a[1] and remains there until line 25.
The value in a[1] at first is 11, then it gets incremented four times - twice by line 13, and once each by lines 17 and 19. At line 23, a[1] is 11+1+1+1+1 = 15, so it prints 15.
27: printf("%d\n", *p); // Why not printing -2 ?
Because in line 25, p is incremented from &a[1] to &a[2]. The value in a[2] starts as -1 and is never changed.
+ 1
Abhay mishra
printf("%d\t%d\t%d\n" , (*p)++ , (*p)++ , *(++p)) ;
//this satatement have undefined behaviour it may output in diferent on different compilers
10 11 11
or
11 12 12
or
12 11 11
from left to right or right to left, undefined by statndards so i just taken one expresion to simplyfy understanding.. And taken only
printf("%d\n" , *(++p)) ;
so output is different than you get..
11
11
12
But with the your statements, you get
13
13
14
Remaining all same.
just look at where pointer locating..
Hope it helps...
+ 1
G'day Brian nicely said.
I think the line:
printf("%d\n", (*(p++ - 2)) - 1);
Post increments p, subtracts 2 from existing location a[1]-2 is a[-1] (out of range but =0), then subtracts 1 from the value.
How this code gets allowed to run is the biggest mystery!
+ 1
HungryTradie good analysis! Boundaries are largely ignored in C, as they would be in assembly language. I think of C as an easier way to compose what I would do in assembly. Such gaffes are too easy to make in both assembly and C, which is why Java was invented. Though sometimes flexibility of breaking boundaries is useful and deliberate, which is why C still is around. You have to be careful in C to the utmost!
0
#include<stdio.h>
int main(){
int a[] = {10, 11 ,-1 ,56 ,67, 5 ,4} ;
int *p , * q ;
p = a ;
q = &a[0] + 3; //now q points to 4th element 56
printf("%d\n", *q); // output : 56
printf("%d\n" , *(++p));
//your way is 'undefined' so just using one.
printf("%d\n", *p); // 11
printf("%d\n",(*p)++); //11 but *p=12 after it
printf("%d\n", (*p)++); //12 but *p=13 still p points to 1st location and *p 13
// p+2 points to 4th element 56 so *(p+2) returns 56 and 56-2=54 but pointer not updated its location stil points to *p = 13
printf("%d\n", (*(p + 2)) - 2); // 54 .
printf("%d\n", *p); //13
//(p-2) is invalid actually caling a[-1] so it returning 0 and 0-1= -1 but p++ cause to point to next location that is -1
printf("%d\n", (*(p++ - 2)-1)); // p++ cause to pointer increment so now p points to -1
printf("%d\n", *p); // output -1
//post increment first uses its value then increments.
**(p+2 != p=p+2) but p++ =>p=p+1
return 0;
}
//hope it clears.