Questions about array and pointer from a beginner - c++

I am new to C++ and to programming in general. I got confused when I learnt the concepts of pointer and array.
Takes int*p = arr; int arr[]={5,1}; as an example. I learnt that arr is also a pointer.
p(a pointer) arr[0]
the thing it stores: [first element address: 601] [5]
its memory : 501 601
address(just make
some fake address)
However, arr(the pointer)
[first element address: 601]
601
Normally, a pointer should have a different address from the array. However, the arr, as the pointer to the first element, has the same address as the first element. So I feel confused. And I wonder whether it is because the memory box of arr[0] is split into two parts: one part for arr[0], and one part for the pointer arr, so that they have the same address in memory.

I learnt that arr is also a pointer.
Then you were taught something wrong, which is probably the reason for your confusion.
If you have int arr[] = {5, 1}; then arr is an array, not a pointer. An array can implicitly be converted to a pointer to its first element. But the array itself is still an array. For example, make an int arr[512]; and check what sizeof(arr) is going to be. If arr were a pointer, then that should be the same as sizeof(int*). But it isn't because arrays are not pointers. They are arrays…
If you write
int arr[] = {5, 1, 3};
int* p = arr;
what you end up with is something like this:
arr
+---+---+---+
0xA0: | 5 | 1 | 3 |
+---+---+---+
p
+-------+
0xB0: | 0xA0 |
+-------+
Somewhere in memory, let's say at address 0xA0, there will be an object that is an array of three int. The identifier arr is just a name that denotes this array object in you code. The array object contains three int objects placed one after the other. The individual ints (elements of the array) are subobjects of the complete array object. Note that the address of the complete array object is the same as the address of the subobject that is the first array element. Nevertheless, there is a difference between the array object arr, which is of type int[3] and encompasses the whole array, and the first element, which is of type int.
Also in memory, let's say at address 0xB0, there will be another object of type int*. The identifier p is just a name that denotes this pointer object in your code. p is a completely separate object from arr. It exists at a completely different address. p was initialized to point to the result of the expression arr. The expression arr denotes our array. Pointers and arrays are completely different things. In what way does it make sense to assign an array to a pointer!? What is going on?
To understand why int* p = arr; works and what it does, let's back up a little and think about how we would actually access an element of arr. If we know the address at which array elements start, we can simply compute the address of any element by just adding the element size times the element index. This is precisely how pointer arithmetic works in C++ (which is not a coincidence): given a pointer p to the first element of an array, we can get a pointer to the i-th element by just adding them together: p + i. In fact, the subscripting operator [] for element access such as p[i] is literally defined as just shorthand notation for *(p + i).
Thus, while arrays and pointers are completely different things, arrays only really become useful once pointers enter the picture. Using an array generally requires accessing its elements. Accessing the elements of an array generally requires pointers. Since you generally need a pointer to the first element to really use an array for anything, arrays can implicitly be converted to a pointer to their first element in C and C++.
When you write p = arr what you're really writing is p = &arr[0]. Because, while you cannot assign an array to a pointer, an array of int can implicitly be converted to an int* that points to the first element of the array. And that int* can be assigned to a pointer. And that's why p in our example above will contain the address of the first element of the array (which happens to be the same as the address of the array).
However, since arrays are arrays, not pointers (they just can be converted to a pointer to the first element if necessary), taking the address of an array like &arr will result in a pointer to the array object itself (which, as we have seen, has the same address as the first element). The type of &arr will be int(*)[3] (pointer to array of three int). Unlike &p, which will actually be a pointer to a pointer to int…
Note: When you write arr[2], what you're really writing is *((&arr[0]) + 2) because the [] operator works on pointers. And arrays are not pointers but can implicitly be converted into a pointer to their first element…

I would suggest that pointers are not a beginner topic in C++, they are mostly just a carry over from C. If you can, you should avoid them and use the STL Containers.
In your code sample, the type of arr is int[2]. You should think of that in memory as looking something like this:
arr --+
|
v
+---+---+
| 5 | 1 |
+---+---+
The value contained in arr is the location of the first element (the 5). arr is essentially a pointer to that 5. The only difference being that the type (int[2]) has also remembered how many elements there are.
The assignment statement p = arr works because p's type is int* which int[] can decay to.

Related

Clarification on the relation of arrays and pointers

I wanted some further understanding, and possibly clarification, on a few things that confuse me about arrays and pointers in c++. One of the main things that confuse me is how when you refer to the name of an array, it could be referring to the array, or as a pointer to the first element, as well as a few other things. in order to better display where my trouble understanding is coming from, I'll display a few lines of code, as well as the conclusion that I've made from each one.
let's say that I have
int vals[] = {1,50,3,28,32,500};
int* valptr = vals;
Because vals is a pointer to the first value of the array, then that means that valptr, should equal vals as a whole, since I'm just setting a pointer equal to a pointer, like 1=1.
cout<<vals<<endl;
cout<<&vals<<endl;
cout<<*(&vals)<<endl;
cout<<valptr<<endl;
the code above all prints out the same value, leading me to conclude two things, one that valptr and vals are equal, and can be treated in the same way, as well as the fact that, for some reason, adding & and * to vals doesn't seem to refer to anything different, meaning that using them in this way, is useless, since they all refer to the same value.
cout<<valptr[1]<<endl;//outputs 50
cout<<vals[1]<<endl;//outputs 50
cout<<*vals<<endl;//outputs 1
cout<<*valptr<<endl;//outputs 1
the code above furthers the mindset to me that valptr and vals are the same, seeing as whenever I do something to vals, and do the same thing to valptr, they both yield the same result
cout<<*(&valptr +1)-valptr<<endl;
cout<<endl;
cout<< *(&vals + 1) -vals<<endl;
Now that we have established what I know, or the misconceptions that I may have, now we move on to the two main problems that I have, which we'll go over now.
The first confusion I have is with cout<< *(&vals + 1) -vals<<endl; I know that this outputs the size of the array, and the general concept on how it works, but I'm confused on several parts.
As shown earlier, if
cout<<vals<<endl;
cout<<&vals<<endl;
cout<<*(&vals)<<endl;
all print out the same value, the why do I need the * and & in cout<< *(&vals + 1) -vals<<endl; I know that if I do vals+1 it just refers to the address of the next element on the array, meaning that *(vals+1)returns 50.
This brings me to my first question: Why does the & in *(&vals+1) refer to the next address out the array? why is it not the same output as (vals+1)in the way that *(&vals)and (vals)have the same output?
Now to my second question. We know thatcout<< *(&vals + 1) -vals<<endl; is a valid statement, successfully printing the size of the array. However, as I stated earlier, in every other instance, valptr could be substituted for vals interchangeably. However, in the instance of writingcout<<*(&valptr +1)-valptr<<endl; I get 0 returned, instead of the expected value of 6. How can something that was proven to be interchangeable before, no longer be interchangeable in this instance?
I appreciate any help that anyone reading this can give me
Arrays and pointers are two different types in C++ that have enough similarities between them to create confusion if they are not understood properly. The fact that pointers are one of the most difficult concepts for beginners to grasp doesn't help either.
So I fell a quick crash course is needed.
Crash course
Arrays, easy
int a[3] = {2, 3, 4};
This creates an array named a that contains 3 elements.
Arrays have defined the array subscript operator:
a[i]
evaluates to the i'th element of the array.
Pointers, easy
int val = 24;
int* p = &val;
p is a pointer pointing to the address of the object val.
Pointers have the indirection (dereference) operator defined:
*p
evaluates to the value of the object pointed by p.
Pointers, acting like arrays
Pointers give you the address of an object in memory. It can be a "standalone object" like in the example above, or it can be an object that is part of an array. Neither the pointer type nor the pointer value can tell you which one it is. Just the programmer. That's why
Pointers also have the array subscript operator defined:
p[i]
evaluates to the ith element to the "right" of the object pointed by p. This assumes that the object pointer by p is part of an array (except in p[0] where it doesn't need to be part of an array).
Note that p[0] is equivalent to (the exact same as) *p.
Arrays, acting like pointers
In most contexts array names decay to a pointer to the first element in the array. That is why many beginners think that arrays and pointers are the same thing. In fact they are not. They are different types.
Back to your questions
Because vals is a pointer to the first value of the array
No, it's not.
... then that means that valptr, should equal vals as a whole, since I'm just setting a pointer equal to a pointer, like 1=1.
Because the premise is false the rest of the sentence is also false.
valptr and vals are equal
No they are not.
can be treated in the same way
Most of the times yes, because of the array to pointer decay. However that is not always the case. E.g. as an expression for sizeof and operand of & (address of) operator.
Why does the & in *(&vals+1) refer to the next address out the array?
&vals this is one of the few situation when vals doesn't decay to a pointer. &vals is the address of the array and is of type int (*)[6] (pointer to array of 6 ints). That's why &vals + 1 is the address of an hypothetical another array just to the right of the array vals.
How can something that was proven to be interchangeable before, no longer be interchangeable in this instance?
Simply that's the language. In most cases the name of the array decays to a pointer to the first element of the array. Except in a few situations that I've mentioned.
More crash course
A pointer to the array is not the same thing as a pointer to the first element of the array. Taking the address of the array is one of the few instances where the array name doesn't decay to a pointer to its first element.
So &a is a pointer to the array, not a pointer to the first element of the array. Both the array and the first element of the array start at the same address so the values of the two (&a and &a[0]) are the same, but their types are different and that matters when you apply the dereference or array subscript operator to them:
Expression
Expression type
Dereference / array subscript expresison
Dereference / array subscript type
a
int[3]
*a / a[i]
int
&a
int (*) [3] (pointer to array)
*&a / &a[i]
int[3]
&a[0]
int *
*&a[0] / (&a[0])[i]
int

cast an C++ array to a vector

Here is the code I found on Leetcode. However I cannot make sense of the following two lines, especially *(&a + 1). And the results show a copy of the array a. Could anyone give some explanation to this? Thanks!
int a[5] = {0, 1, 2, 3, 4};
vector<int> v4(a, *(&a + 1));
The examples that you normally face when constructing a vector from an array usually looks like the following:
int a[5] = {...};
vector<int> v4(a, a + 5 );
// or vector<int>(a, a+sizeof(a)/int); // automatically calculate num elems inside a
The example above simply shows you want to construct a vector using all the elements inside array "a". "a" in this example is just the address to the starting element of the array, then you add 5 to get the address of the last element. A more intuitive way to write this would be:
vector<int> v4(begin(a), end(a));
Unless of course you don't want all the elements of a in v4
Now the example you have given us is the shorthand of the first example where you don't need to explicitly state the size of the array.
I'm assuming you are just confused with the second argument of the vector constructor.
The second argument just returns the address of the last element of array "a". But how?
Well let's break it down:
&a returns the address to the "a[]". Essentially a pointer to the array "a". Now if you add one to this address, you will get a pointer to the address "a[0]" + sizeof a[] which will point to the last element of address a. Compare this to the first example above. You had to add 5, why is this not the case here? Well you are working with different units. &a points to the starting address of a[] rather than the address of the first element of the array. So you are essentially moving the address in units of a[5] rather than units of int.
Then finally you have the dereference operator "*" to dereference the pointer and get the address of array[] for the last element.
a is type a[] and &a is type *a[] so the dereference is needed to make it the same type otherwise you get a compiler error.
TLDR: You are getting the address for the last element using different methods. The +1 operator behaves relative to the type you are dealing with. a + 1 is the same as starting address of "a" + sizeof 1 integer. &a + 1 is the same as starting address of a[] + size of a[].
You're getting confused by array decay. a is the array "as a whole". It decays into a pointer pointing to the first element in MOST contexts, but the operand of unary-& is one of the few that it does not. So &a gives you the address of the array as a whole, not the address of the first element. These are the same place, but have different types (int (*)[5] vs int *) and that different type means that pointer arithmetic is different.

Array and pointers in c++ [duplicate]

This question already has answers here:
C/C++ int[] vs int* (pointers vs. array notation). What is the difference?
(5 answers)
Why am I being told that an array is a pointer? What is the relationship between arrays and pointers in C++?
(6 answers)
Closed 6 years ago.
I often hear that the name of an array is constant pointer to a block of memory therefore statement like
int a[10];
and
int * const p= a;
must be equal in a sense that p is pointer that points to the same block of memory as array a[] and also it may not be changed to point to another location in memory.
However if you try to print sizeof these two pointers you get different results:
cout<< sizeof(a); // outputs size of 10 integer elements
While
cout<< sizeof(p); // outputs sizeof pointer to int
So, why do compilers treat these two differently? What's the true relation between arrays and pointers from compiler point of view?
I often hear that the name of an array is constant pointer to a block of memory
You've often been mislead - or you've simply misunderstood. An array is not a constant pointer to a block of memory. Array is an object that contains a sequence of sub-objects. All objects are a block of memory. A pointer is an object that contains an address of an object i.e. it points to the object.
So in the following quote, a is an array, p points to the first sub-object within a.
int a[10];
and
int * const p= a;
must be equal in a sense that p is pointer that points to the same block of memory as array a[] and also it may not be changed to point to another location in memory.
If that is your definition of equal, then that holds for non-array objects as well:
char c;
int * const p = &c;
Here p "points to the same memory as c" and may not be changed to point to another location in memory. Does that mean that char objects are "equal" to pointers? No. And arrays aren't either.
But isn't a (the name of the array), a constant pointer that points to the same element of the array?
No, the name of the array isn't a constant pointer. Just like name of the char isn't a constant pointer.
the name of an array holds the address of the first element in the array, right?
Let's be more general, this is not specific to arrays. The name of a variable "holds the address" of the object that the variable names. The address is not "held" in the memory at run time. It's "held" by the compiler at compile time. When you operate on a variable, the compiler makes sure that operations are done to the object at the correct address.
The address of the array is always the same address as where the first element (sub-object) of the array is. Therefore, the name indeed does - at least conceptually - hold the same address.
And if i use *(a+1), this is the same as a[1], right? [typo fixed]
Right. I'll elaborate: One is just another way of writing another in the case of pointers. Oh, but a isn't a pointer! Here is the catch: The array operand is implicitly converted to a pointer to first element. This implicit conversion is called decaying. This is special feature of array types - and it is the special feature which probably makes understanding the difference between pointers and arrays difficult the most.
So, even though the name of the array isn't a pointer, it can decay into a pointer. The name doesn't always decay into a pointer, just in certain contexts. It decays when you use operator[], and it decays when you use operator+. It decays when you pass the array to a function that accepts a pointer to the type of the sub-object. It doesn't decay when you use sizeof and it doesn't decay when you pass it to a function that accepts an array by reference.

Why say that a 2-dimensional array is a "pointer to a pointer?"

Suppose we have that the following 2-dimensional array:
int multi[3][3];
As I understand it, we can then say that multi is a "pointer to a pointer", or -- at the very least -- we can do something like the followiong:
int **p_p_int = multi;
Question: Why don't we say that multi is a "pointer to a pointer to a pointer to pointer", since multi points towards the address of its first element, which itself points to a pointer, which points towards the address of multi[0][0], which itself points to the value of multi[0][0].
This seems to be 4 objects that point (here I'm counting addresses as pointers).
Now you might say "but addresses aren't pointers, even though pointers can equal addresses", in which case it also seems weird to say that a 2-dimensional array is a "pointer to a pointer", since it's actually a pointer to an address to a pointer to an address (to a value).
I feel like I have mananaged to confuse myself quite a bit here :)
A 1d array converts to a pointer rather than being one — e.g. you can reassign a pointer, you cannot reassign an array.
A literal 2d array isn't stored in the way described below.
However a 2d array can be achieved by a pointer to a pointer if:
int **array2d is a pointer. It points to an array. That array contains pointers.
Because array2d points to an array of pointers, array2d[n] is also a pointer. But it's a pointer to an array of integers.
So that's two pointers, total.
In pseudo code, the steps to look up the item at (m, n) are:
add m to array2d to index that array. Read pointer, p from calculated address;
add n to p to index that array. Read integer from calculated address.
The job of a pointer is to point towards something. Just because something is both a pointer and points to something else doesn't make it a pointer to a pointer, unless that something else is a pointer.
So let's break this down:
multi points towards the address of its first element,
That makes it a pointer
which itself points to a pointer,
That makes it a pointer to a pointer.
which points towards the address of multi[0][0],
No. It contains the address of multi[0][0], it doesn't point to it.
which itself points to the value of multi[0][0]
Well, of course. It's a pointer, pointers point to values, that's their job. That doesn't make them pointers to pointers, it makes them pointers to values.
This seems to be 4 objects that point (here I'm counting addresses as pointers).
Sure, but two of those pointings are the very same pointing just counted twice. You say X is a pointer that contains a value that points to something as if that was two separate pointings. The job of a pointer is to have a value that points to something, that's what makes it a pointer in the first place. It's two ways of saying the same thing, "X is a pointer" = "X contains a value (of a type) that points to something".
Saying that multi is a pointer to a pointer is just wrong. It is a 2D array.
multi can not be converted to a ** - only to *
A pointer to pointer would obviously point to a pointer. multi is not doing that. You'll find an integer at that location - not a pointer - simply because multi is not an array of pointers. multi[n] may also be converted to a * but the converted value is not taken from a place where it was stored - it is just calculated from multi.
Don't think of a 2D array like:
int a[3];
int b[3];
int c[3];
int* x[3] = {a, b, c};
cause that is simply not how 2D arrays work.
All pointer values you get from a 2D array are calculated values - not stored values.
I think that there are two unrelated stuff here that you are mixing up:
the name of any array of the type T[][][]...n...[] decayes into T*[][][]...n-1...[] for example:
int arr [7] decayes into int* arr
std::fstream arr[2][2] decays into std::fstream* arr[2]
by decaying, we mean that a function which can get T can also accept T' which T' is the decayed type of T
you can dynamically create psuedo 2 dimentional arrays by using pointer to pointer and dynamic allcoation
int** psuedeo2DimArray = new int*[10];
for (auto i=0U;i<10;i++){
psuedeo2DimArray[i] = new int[10];
}
In all cases, the type of multi is int[2][2] and nothing else.

how do arrays work internally in c/c++

I was wondering how do arrays work in c. I end up with an hypothesis and I'd like to know if I am right or not.
We know arrays are a sequence of adjacent memory cases(boxes), where each box has the size of the type it stocks (i.e if INTs one box has a size = sizeof(int) and an array of 3 INTs takes in memory adjacent places of 3 sizeof(int) )
Now we also know that we can dynamically allocate memory for an array of a certain type (malloc in C, new in C++).
what makes me wonder is the fact that an array has for origin the the address of the first box of the array and the first value (the value in the later box) when calling it with the bracket [0] is array[0] == *(array+0) == *array (whether array was declared "type * array" or "type array[]" or "type array[size]") and "array" called that way whether define as a pointer or an array ("type * array" or "type array[]" or "type array[size]") is the address of the first box.
I end up thinking and I'd like a confirmation on this: arrays when even declared with the square brackets ([]) are actually in memory a sequence of n pointers each containing (having as a value not as an address) the address of a memory box Bi containing the actual value + those memory boxes (B0,...,Bn each containing the actual values). such that in the and when one declares "int array[5]" the program actually allocate 5 adjacent boxes of int pointers P0,P1,..,P4 and 5 int sized memory places scattered all over the computer memory B0,B1,...,B4 where the value of Pi is the address of Bi
Am I right or wrong!!?? Thank you!
arrays when even declared with the square brackets ([]) are actually in memory a sequence of n pointers each containing [...] the address of a memory box Bi containing the actual value + those memory boxes
Nope.
It sounds like you're puzzled how array[0] == *(array+0) == *array could be true both for an array declared as int array[10]; and int *array = ...;. A perfectly reasonable question; We're told that for a pointer ptr the expression *ptr gets the value the pointer is pointing at, so when we use the same syntax with an array where are the addresses that we're dereferencing?
Here's the secret: The array index operator ([]) does not work on arrays in C and C++. When you apply it to an array the language implicitly converts the array into a pointer to the array's first element. Thus adding to an array or dereferencing an array appears to behave the same as adding or dereferencing a pointer.
int array[10];
// These lines do exactly the same thing:
int *ptr1 = &array[0]; // explicitly get address of first element
int *ptr2 = array; // implicitly get address of first element
So arrays really are a contiguous set of elements in memory where each element really is the value, not a pointer to another location containing the value. It's just that the way arrays are defined means that they often convert to a pointer implicitly and so it seems like there are pointers when really there's just an implicit conversion.
Arrays are stored contiguously in the virtual memory. However, the physical memory addresses that they map to may or may not be contiguous.
And the array elements do not store a pointer to point to the next element. Only the value is stored.
Think of it as this:
array[n] is simply a syntactic sugar for *(array + n).
And no, there are no pointers, the array actually contains the values in a continuos memory range.
The array does not consist of any pointers. The elements of an array are stored on the heap whereas the reference to those elements is stored on the stack. If you declare an array called values of type int and it consists of 5 elements.
The variable values is a pointer to the first value values[0] stored on the heap, it is also referred to as the base address which is the address of the first element of the array. You might wonder that how would the code find the other elements of the array. values[1] can be dereferenced by *(values+1) or at a low level it is like this *(&values + n*sizeof(values[0])) where n is the index of the element you want to dereference.
So you get the other elements of an array by just adding the size of the element to the memory. This is because the elements of an array are stored side-by-side in memory or technically stated, the blocks of memory share the same border.
An array does not have any pointers, an array like data-structure that contains pointers is called a linked list.
You can learn about the internal working of arrays here