Printing array using pointer logic

Hello,

I was trying to print an array of integers using pointer logic to it. So, as an integer uses 4bytes of memory, for me to jump from cell to cell of the array, I need to sum up 4 units into the pointer address. This way, why can't sum 4 to the pointer instead of summing only 1?

1
2
3
4
5
6
7
8
9
10
11
12
13
    int arr[10];
    
    for (int i = 0; i < 10; i++) {
	arr[i] = i; 
    }
    //why to add 1 by 1 instead of summing 4 to the address every time? 
    for (int i = 0; i < 10; i++) {
	cout << "addr: " << arr + i <<" Value: "<< *(arr+i)<< endl;
        //like that
	//cout << "addr: " << arr + 4 <<" Value: "<< *(arr+4)<< endl;

    }
    


Thanks!
C++ knows its an |int *| so it knows that each one takes sizeof(int) already. So +1 knows to add 4 for you.

you CAN manually do this.
unsigned char* ucp = (unsigned char*)arr;
for(x = 0; x < 40; x+=4)
cout << (int*)(ucp[x]);

but that is a big mess. let the language do it for you.
Got it! Thanks!
Topic archived. No new replies allowed.