Reputation: 647
this was an example given to us in class. Could someone explain to me why this prints 29 addresses instead of 29 "0" (zeroes) ?
int num[29];
is an array which has set aside 29 addresses for 29 integers -i get that part, but in the for loop you arent u printing the values IN those addreses rather than the addresses themselves?
also, whats the difference between (num+i)
and (num[]+i)
?
I'm a little confused..
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int num[29];
for (int i=0;i<29;i++)
cout << (num+i) << endl;
return 0;
}
Upvotes: 0
Views: 4643
Reputation: 68668
A declaration such as:
int num[29];
defines a contiguous array of 29 integers.
To access elements of the array use num[i]
where i is the index (starting at 0 for the 1st element).
The expression num
on its own gives a pointer (memory address and type) of the first element of the array.
The expression ptr + i
(where ptr is a pointer and i is an integer) evaluates to a pointer that is i positions (in units of the type of pointer) after ptr.
So num + i
gives a pointer to the element with index i.
The expression &a
gives a pointer to some object a
.
The expression *ptr
gives the object that some pointer ptr is pointing at.
So the expressions a
and *(&a)
are equivalent.
So num[5]
is the same as *(num+5)
and num+5
is the same as &num[5]
and num
is the same as &num[0]
When you print a pointer with cout it will show its address.
When you print an object it will print the value of the object.
So
cout << num + 5;
will print the address of the 5th (zero-indexed) element of num
and
cout << num[5];
will print the value of the 5th (zero-indexed) element of num
Upvotes: 3
Reputation: 372814
The reason for printing addresses is that
(num+i)
Is the address of the i
th element of the array, not the i
th element itself. If you want to get the i
th element, you can write
*(num + i)
Or, even better:
num[i]
As for your second question - the syntax (num + i)
means "the address i
objects past the start of num
, and the syntax (num[] + i)
is not legal C or C++.
Hope this helps!
Upvotes: 9