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

Luke Autry
  • 61
  • 5
  • `nums` is a pointer and `nums[i]` dereferences the pointer at index i – phuclv Jul 02 '21 at 02:23
  • 1
    Does this answer your question? [What does "dereferencing" a pointer mean?](https://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean) – phuclv Jul 02 '21 at 02:23

1 Answers1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770