C programming, pointers

#include<stdio.h>
int main(){
int a={10,11,-1,56,67,5,4};
int *p,*q;
p=a;
q=&a[0]+3;
printf(“%d %d %d\n”,(*p)++,(p)++,(++p));
printf(“%d\n”,p);
printf(“%d\n”,(p)++);
printf(“%d\n”,(p)++);
q–;
printf(“%d\n”,(
(q+2))–);
printf(“%d\n”,
(p+2)-2);
printf(“%d\n”,
(p++ -2)-1);
return 0;
}

could you pls tell me why are we getting -3 at the end i am getting -2.

It’s impossible to provide an answer because the format of the forum uses the symbol “*” as a way to create italic letters. Some pointers are missing.

Please retry using writing your code using this format with these symbols:

```
Code here
```

#include<stdio.h>
int main(){
int a={10,11,-1,56,67,5,4};
int *p,*q;
p=a;
q=&a[0]+3;
printf(“%d %d %d\n”,(*p)++,(p)++,(++p));
printf(“%d\n”,p);
printf(“%d\n”,(p)++);
printf(“%d\n”,(p)++);
q–;
printf(“%d\n”,(
(q+2))–);
printf(“%d\n”,
(p+2)-2);
printf(“%d\n”,
(p++ -2)-1);
return 0;
}

Screenshot 2024-04-25 113531

I see.
Are you using Windows by any chance?

First, remember that a pointer only stores a memory direction. It doesn’t know what you are storing nor what you want to do with it. In an int pointer (or any native variable), you can store either a pointer to a value or either an array.
If you can move from one element to another of the array “a” with your pointer “p”, it is due a C feature that should be handled with care. Unlike a common static or dynamic array, a pointer will not tell you when you are out of bounds.

That’s the case.

What is happening is that you are trying to access to a memory location out of bounds of your “a” array. You begin with the pointer “p” adressing to a[0]. Then you move you pointer 4 bytes to the right in your first print (++p), i.e. theoretically in a[1].

You don’t move your pointer until the last 2.

You try to print *(p+2)-2 with is supposed to be a[3]-2, i.e., 54
Finally, you move to (p++ -2)-2, i.e. printing a[-1] -2 (out of bounds)

Why -1?
Because the the operations “++” and “–” work before and after the sensence (depending on were you write them.

This is, when you wrote “++p” in your first sentence, that meant you were going to work on a[1] instead of a[0], and everything was done in that memory place.

When you wrote (p++ -2), that meant that the variable “p” would have moved AFTER the printf. So, to the printf’s concern, the “p” was still in a[1] to that moment. Therefore, 1 - 2 is -1. Out of bounds.

Now, why your parterns got a different number? Well, that’s because that was on thier PC on that memory place, and printf read it. It’s undefined. It could’ve been anything.

Windows systems tend to write little numbers (I don’t know why)

While Linux systems tend to write bigger numbers.

image

1 Like

Thanks a lot for your help i was so confused i was this one