0

Can someone tell me how this compiles. How can you assign an integer array element to a pointer array element? The weird this is that the output suggests that nums[i] is an integer rather than a pointer, however nums was defined as a pointer.

#include <iostream>
int main() {
   int n;
    int *nums = NULL;
    nums = new int[n];  // Assign pointer nums to a address in heap allocated for a integer array of n-elements.
    n=5;
    int Array[n] = {5,4,3,6,8};
    
    for(int i=0; i<n; i++) 
    {
   nums [i] = Array[i];
   std::cout << nums[i] << " , " << &nums[i] << std::endl;
    }

    delete []nums;

    return 0;}

I get the following output:

5 , 0x786cd0
4 , 0x786cd4
3 , 0x786cd8
6 , 0x786cdc
8 , 0x786ce0

Thanks for any help

2
  • nums is a pointer and nums[i] dereferences the pointer at index i Commented Jul 2, 2021 at 2:23
  • 1
    Does this answer your question? What does "dereferencing" a pointer mean? Commented Jul 2, 2021 at 2:23

1 Answer 1

2

How can you assign an integer array element to a pointer array element?

nums is a pointer to a dynamic array of int elements, in this case to the 1st int in the array. Dereferencing nums[i] yields an int& reference to the ith element in the array.

Array is a fixed array of int elements. When a fixed array is accessed by its name, it decays into a pointer to the 1st element. So, dereferencing Array[i] also yields an int& reference to the ith element in the array.

Thus, nums[i] = Array[i]; is simply assigning an int to an int. Nothing weird about that.

the output suggests that nums[i] is an integer rather than a pointer

That is correct, it is.

however nums was defined as a pointer

That is also correct. It is a pointer to an int, in this case the 1st int in the dynamic array.


Also, on a side note, your code has undefined behavior because n is uninitialized when used to allocate nums, and int Array[n] is non-standard behavior since n is not a compile-time constant.

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

1 Comment

My guess is they assumed nums would somehow be an array of pointers.

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.