0

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;
}

2 Answers 2

9

The reason for printing addresses is that

(num+i)

Is the address of the ith element of the array, not the ith element itself. If you want to get the ith 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!

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.