0

I am learning C++ and have become a little confused to how a Pointer to an Integer Value and a Pointer to an Array differ... See my code below:

int main(void) 
{
    int* ptrOne;
    int VarOne = 25;

    ptrOne = VarOne; 

    int* ptrTwo;
    int ArrayTwo[6];
    ArrayTwo[0] = 2; //ect for the rest of the array, omitted here.

    ptrTwo = ArrayTwo;
}

Pointers are just variables that hold an address.

For the line ptrOne = VarOne, it shoves the VALUE of 25 into ptrOne.

For the line ptrTwo = ArrayTwo, it shoves the ADDRESS of ArrayTwo[0] into ptrTwo.

Why is ptrTwo = ArrayTwo equivalent to ptrTwo = &ArrayTwo[0], but ptrOne = VarOne is NOT equal to ptrOne = &VarOne?

Is this due to the fact the operation is happening to an array vs an int?

Thanks in advance for any help, I have stepping through this code in my compiler and looked at the addresses in memory and the associated values, I did also read the answer for how to differentiate integer pointer and integer array pointer, but it did not fully explain the differences.

sdub0800
  • 139
  • 1
  • 9

2 Answers2

2

Why is ptrTwo = ArrayOne equivalent to ptrTwo = &Array[0]

Because in C the name of the array is the address of the first element. You may want to check out further why: How come an array's address is equal to its value in C?

but ptrOne = VarOne is NOT equal to ptrOne = &VarOne?

Because VarOne is a single variable, so VarOne is the value of the variable itself, not the address of that variable.

Actually this code should be an outright error if you switch on compiler warning (-pedantic-errors) which tells you that you can't convert a pointer type to int.

error: assignment makes pointer from integer without a cast [-Wint-conversion]
artm
  • 17,291
  • 6
  • 38
  • 54
0
int A[5]={0,1,2,3,4};

The name of the array A is a constant pointer to the first element of the array. So A can be considered a const int*. Since A is a constant pointer, A = NULL would be an illegal statement. Arrays and pointers are synonymous in terms of how they use to access memory. A[0] returns the value in [the pointer of the array's first element]+0 yet returns the array element with the index of '0'.

int* ptr= A; //= int* ptr= &A[0];

So since int is considered as a data type we can't use it as a pointer. when we want to declare a static pointer of an int value it's written with the following syntax :

int X= 25;
int* ptr= &X;