I wrote the next code:
int main()
{
int arr[] = {1,2,3,4,5};
std::cout <<"&arr: " <<&arr<<"\narr&:"<<&(arr+1);
return 0;
}
why is &arr compile and gives the address of arr at the position 0,
and &(arr+1) doesn't compile?
(I have expected it will return the address of arr at the position 1)
&arr is not an address "at a position", but the address of the entire array. You can see this via the difference in types:
&arr is the address of the array and has type ARR*, where ARR is the type int[5]. When combined, this type looks like int(*)[5].
&arr[0] is the address of the first element. It has type int*.
Now the actual values are the same because the array object starts at its first element, but it helps to not focus on that when trying to understand arrays vs. pointers.
When you say arr + 1, what's actually happening is that arr is being silently converted from an array (int[5]) to a pointer (int*) to the first element of the array. You then advance this pointer by one int. This results in an int* pointing to the second element of the array. This is the result you wanted to print and is equivalent to &arr[1].
Remember that & takes the address of an object. It's meaningless to take the address of a temporary like the pointer arr + 1. &(arr + 1) is equivalent to &(&arr[1]). They both try to take the address of something that logically doesn't have an address of its own. Remember that a pointer can store an address as its value, but the only reason & comes into play is because you can use it to obtain the address of an object, which can then be stored into a pointer. &ptr is the address of ptr itself, not the value stored in ptr.
In short, be consistent with what you want. Both of the following will print the address of the first element and the address of the second element. Both print two int*s since your intent is about individual elements, not the whole array:
std::cout << "First: " << &arr[0] << "\nSecond: " << &arr[1];
std::cout << "First: " << arr << "\nSecond: " << (arr + 1);
Related
This question already has answers here:
What is array to pointer decay?
(11 answers)
Passing the address of an array into a function in C++
(3 answers)
Why do the following have the same value: the pointer to an array, the dereferenced pointer to the array?
(3 answers)
How come an array's address is equal to its value in C?
(6 answers)
Closed 9 months ago.
I am a beginner to data structures and algorithms, started studying the pointers now and before asking the question here I read this recommended post but I couldn't understand it so I am asking the query here.
I have been told by a friend that array's name is a pointer to the first value in the array, as arr returns the address of arr[0], arr+1 returns address of arr[1], so when I write this
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i = 10;
int arr[3] = {1, 2, 3};
int *ptr = &i;
cout << arr << " " << &arr << endl;
cout << ptr << " " << &ptr;
return 0;
}
Both arr and &arr give same result
0x61ff00 0x61ff00
While ptr and &ptr give different results
0x61ff0c 0x61fefc
Can someone tell me why is this happening ?
Arrays are not pointers!
Arrays do decay to a pointer to their first element in all sorts of circumstances. For example std::cout << arr; actually prints the memory address of the first element of the array. std::cout << &arr; prints the memory address of the array. As the address of the first element is the same as the address of the array you see the same value.
However, just because they have the same value, does not mean they are the same. arr can decay to a int*, while &arr is a pointer to an array, a int(*)[3].
I hope the following will help to clear things up a little:
#include <iostream>
#include <type_traits>
void make_it_decay(int x[]) {
std::cout << std::is_same_v< decltype(x), int*> << "\n";
}
int main() {
int arr[3] = {1,2,3};
//std::cout << (arr == &arr) << "\n"; // does not compile !
std::cout << (arr == &(arr[0])) << "\n";
std::cout << std::is_same_v< decltype(arr), int[3]> << "\n";
std::cout << std::is_same_v< decltype(&arr),int(*)[3]> << "\n";
std::cout << std::is_same_v< decltype(&arr[0]), int* > << "\n";
make_it_decay(arr);
}
output:
1
1
1
1
1
I use decltype to infer the type of certain expressions and std::is_same_v to see if the expressions are of same type.
arr is of type int[3]. It is an array. It is not a pointer.
&arr is the address of the array. It is a pointer to an array with three elements, a int(*)[3].
&arr[0] even though it has the same value as &arr is of different type. It is a pointer to int, an int*.
When we pass arr to a function then it decays to a pointer to the first element of the array. And we can see that inside the function x is int*.
Now to your quesiton...
Above I tried to lay out what happens when you write std::cout << arr. Pointers are different, because ... well arrays are not pointers.
std::cout << ptr; // prints the value ptr
std::cout << &ptr; // prints the address of ptr
Perhaps some visualization helps. The difference in types gets most apparent when incrementing the pointers
-------------------
| arr |
-------------------
| 1 | 2 | 3 |
-------------------
^ ^ ^
&arr | &arr + 1
&arr[0] |
&arr[0] + 1
array's name is a pointer to the first value in the array
The above statement is not technically correct. What happens is that in many contexts the array decays to a pointer to its first element due to type decay. This means, in your example, when you wrote std::cout << arr, there was an implicit array-to-pointer conversion which converted your array arr of type int[3] to a pointer to its first element which is the type int*.
Note
Note also that even though the decayed pointer and the address of the array both have the same value their types are different. The decayed pointer is of type int* while the &arr is of type int (*)[3].
#include <iostream>
int main() {
int arr[2] = {1, 2};
int *p;
// p = &arr; // Does not compile
p = &arr[0]; // compiles
std::cout << "&arr = " << &arr << std::endl;
std::cout << "&arr[0] = " << &arr[0] << std::endl;
}
When I try to print the address both print the same address. But when I try to assign p = &arr it does not compile. Is there something in standard that says something against assigning address of array to pointer. I just wanted to know the reason why p = &arr does not compile?
Clang actually says error: cannot initialize a variable of type 'int *' with an rvalue of type
p = &arr;
is a compiler error because the type of &arr is int (*)[2] -- pointer to an "array of 2 ints". Hence, it cannot be assigned to p, whose type is int*.
Even though &arr and &arr[0] evaluate to the same numerical value, they are different types.
So you have this:
arr[0] is the first item in memory
arr[1] is the second item in memory
This is equivalent to the following:
*((int*)arr + 0) is the first item in memory
*((int*)arr + 1) is the second item in memory
"Dereference" the pointer, this lets you access the memory you want instead of the number which represents it in memory (the pointer):
*((int*)arr + 0)
This is equivalent to:
arr[0]
If you wanted the address of any item you can do as shown here:
(int*)arr + Index
The address of the first item is the memory address of the start of the array, so the address of the array AND the first item is:
(int*)arr + 0 or just (int*)arr
Your code here gets the address of the first item, which is the same as the address of the array:
p = &arr[0]; // compiles
Whenever you place an ampersand ( & ) its equivalent to getting the address of, so here you are getting [the address of the address of the array], this is not the same as the [address of the array]
p = &arr; // Does not compile
The type of the address of the address of the array is:
int (*)[2];
Not:
int *p;
That is why it doesn't compile, the types don't match.
To help with type related errors like this one you can use typeid and decltype, in C++ this lets you print the name of the type in question.
Like this
#include <iostream>
using namespace std;
int main()
{
int arr[2] = {1, 2};
std::cout<< "typeid ptr_array is " << typeid(decltype(&arr)).name() << "\n";
std::cout<< "typeid ptr_item is " << typeid(decltype(&arr[0])).name() << "\n";
return 0;
}
The result is:
ptr_array is PA2_i (Pointer to Array of size 2 with int)
ptr_item is Pi (Pointer to int)
"P" from typeid means pointer, "A" means array.
You can play around yourself here:
https://wandbox.org/permlink/RNNxjTMSUnLqUo6q
Can somebody explain to me why this code works?!!
I know A holds &A[0] and it is not a real pointer as if you cout<<&A you would get &A[0], but this result looks very strange to me.
int main()
{
double A[] = {2.4, 1.2, 4.6, 3.04, 5.7};
int len = *(&A+1) - A; // Why is this 5?
cout << "The array has " << len << " elements." << endl;
return 0;
}
And why this code doesn't work? And how can you make it work?
void test(double B[])
{
int len = *(&B+1) - B;
cout << len << endl;
}
int main()
{
double A[] = {2.4, 1.2, 4.6, 3.04, 5.7};
test(A);
system("pause");
return 0;
}
The expression is parsed like this:
(*((&A) + 1)) - A
The probably vexing part is that for some (but not all!) parts of this expression, the array decays to a pointer to the first element. So, let's unwrap this:
First thing is taking the address of the array, which gives you a pointer to an array of five elements.
Then, the pointer is incremented (+ 1), which gives the address immediately following the array.
Third, the pointer is dereferenced, which yields a reference to an array of five elements.
Last, the array is subtracted. It is only here that the two operands actually decay to a pointer to their first elements. The two are the length of the array apart, which gives the number of elements as distance.
&A takes the address of A itself. The type of A is double[5].
When you take the address of A itself and increment that pointer by 1, you are incrementing it by sizeof(double[5]) bytes. So now you have a pointer to the address following the A array.
When you dereference that pointer, you have a reference to the next double[5] array following A, which is effectively also a double* pointer to the address of A[5].
You are then subtracting the address of A[0] (an array decays into a pointer to its first element), and standard pointer arithmetic gives you 5 elements:
&A[5] - &A[0] = 5
Hello i'm a noob in programming, i have a small doubt regarding pointers
#include<iostream>
using namespace std;
int main()
{
int myAge = 16;
int* agePtr = &myAge;
cout << "address of pointer" << agePtr << "Data at memory address" << *agePtr << endl;
int badNums[5] = {4, 13, 14, 24, 34};
int* numArrayPtr = badNums;
cout<< "address" << numArrayPtr << "value" << *numArrayPtr << endl;
numArrayPtr++;
cout<< "address" << numArrayPtr << "value" << *numArrayPtr << endl;
return 0;
}
In the first case while pointing an integer i use &myAge where as in
the second case of incrementing Arrays if i use &badNums the compiler
is returning an error, but if i use badNums its compiling why should
we use badNums instead of &badNums in the second case?
how can I increment the value in integer using pointers?
Arrays implicitly decay to pointers, as per the rules of c++. There are many implicit conversions in c++, this is one of them. When assigning an array to a pointer, it provides you with a pointer to the first element in the array.
Taking the address of an array (&badNums) will yield a pointer to the array, not to the first element. Array pointers are slightly more complicated and encode the size of the array in the type. The correct type for that assignment would be int (*numArrayPtr)[5] = &badNums; where numArrayPtr is a pointer to an array of 5 ints.
To increment a value pointer to by a pointer, you must first dereference that pointer using operator * just like if you wanted to read from or write to that value. It would look like (*numArrayPtr)++;.
In the first case, using &myAge refers to the address of that integer value. The reason why you must use badNums instead of &badNums when doing assignment to the integer pointer is because badNums is already an integer pointer. Arrays implicitly decay into pointers, so using &badNums in that assignment would work if you were doing:
int **numArrayPtr = &badNums;
which is just a pointer to a pointer to the address of badNums. So,
int *numArrayPtr = badNums;
just means that we have a pointer to the address of badNums.
When we have an integer pointer like this, you can increment the value of each integer in the array by doing this:
for (int i = 0; i < 5; i++){
numArrayPtr[i]++;
}
or, we can do the same thing without using array notation:
for (int *i = numArrPtr; i != numArrPtr + 5; i++){
(*numArrPtr)++;
}
I hope that answers your questions fully.
I have a small doubt regarding pointers
Just like i in badnums[i] is an index within array badnums[], a pointer is an index to something stored in memory. Since any variable is stored in memory, you can access the contents of a variable with a pointer to whatever it contains (which is what languages implicitly do when using variables in your code).
The difference is that with pointers you must know the type of what the pointer designates, while an index uses the known type of the indexed elements of the variable it points to... because sooner than later you will iterate the contents of some known variable using a pointer.
For example:
int *p;
int a[2] = {1, 2};
p1 = a;
I was wondering where does c++ store the information of memory space of each element? I mean, when I do this:
cout << p << endl;
I only can get the memory address of that array, there is obviously no information related to the "memory length" of single element. But I think there should be some place that the language can refer to the space of memory space of each element. Since if I go on the call this:
cout << *++p << endl;
I can get the second element of that array no matter what type of element in that array and the corresponding space of memory of single element. The language is able to automatically kind of jump over the certain space memory to get the right start place of the next element and its address.
So, again, my question is: Where is the information of the memory space of element in that array stored? Or is there something like "\0" at the end of each element to signify the end of one element in that array, so the *++p is about to get to the next right place?
where does the information of memory space of each element of that array store?
When you use:
int *p;
int a[2] = {1, 2};
p = a;
memory for the elements of a are in the stack. They memory is contiguous. p points to the first element of a.
Regarding:
I can get the second element of that array no matter what type of element in that array and the corresponding space of memory of single element. The language is able to automatically kind of jump over the certain space memory to get the right start place of the next element and its address.
Yes, that is correct.
From a purely numerical point of view,
p+1 == p + sizeof(*p)
sizeof(*p) can be computed at compile time. There is no need for any run time information. There is no need for markers to signify the end of an element.
The memory in an array is contiguous, so yes incrementing a pointer will get you from one element to the next element.
The way that it knows how far in memory to go to get to the next element is by the type of the pointer, in this case it is an int*, so it knows to increment by sizeof(int) to get to the next element.
It doesn't. C++ has no runtime information about the types of variables. It simply interprets the data behind the pointer as the type you gave to it in your source code. Take the following code for example:
void f(int *) { std::cout << "Integerpointer" << std::endl; }
void f(char *) { std::cout << "Charpointer" << std::endl; }
int i = 9;
int * p = &i;
f(p);
This will print Integerpointer because the compiler knows at compile time that the type of p is int *. The following code will print Charpointer because the type is changed (the compiler interprets the pointer different):
void f(int *) { std::cout << "Integerpointer" << std::endl; }
void f(char *) { std::cout << "Charpointer" << std::endl; }
int i = 9;
int * p = &i;
f(reinterpret_cast<char *>(p));
The compiler substitutes f() with the matching function call in your source code. So the interpretation of the underlying data is done at compiletime.
To address your array question:
The compiler knows the sizes of the elements at compile time. It then adjusts the pointer addition when accessing the elements and puts the size hard coded in your machine code. If you know a bit assambly you can look at the assambly code and see this effect.