0

Pointers with array is not working with - backward operator, why?

#include <stdio.h> int main() { int a[5] = {22, 33, 44, 55, 66}; int *ptr = NULL; int i; ptr = a; for (i = 4; i >=0; i--) { printf("%d ", *(ptr - i)); } } showing address locations not array elements

4th Oct 2018, 1:12 PM
प्रतिक गुमगावकर
प्रतिक गुमगावकर - avatar
4 Respuestas
+ 1
As I mentioned before, use *(ptr + i) instead, since you want the locations that come after ptr, not before it. https://code.sololearn.com/cuNfV70SCo5G/?ref=app
4th Oct 2018, 1:47 PM
Shadow
Shadow - avatar
0
The issue is that ptr (and a) is a pointer to the beginning of the array, the first element. Decreasing this pointer by i means accessing elements that are out of the bounds of the array, i.e. random memory spaces with garbage values. It should work with *(ptr + i) though.
4th Oct 2018, 1:23 PM
Shadow
Shadow - avatar
0
what should I do to reverse print array elements
4th Oct 2018, 1:32 PM
प्रतिक गुमगावकर
प्रतिक गुमगावकर - avatar
0
ty bro!
4th Oct 2018, 1:50 PM
प्रतिक गुमगावकर
प्रतिक गुमगावकर - avatar