This question already has answers here:
Why are `&array` and `array` pointing to the same address?
(2 answers)
How come an array's address is equal to its value in C?
(6 answers)
Closed 1 year ago.
I am confused about array usage as pointer and result of that. Let me explain. When I try this
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int *myPointer = &a;
cout << "*myPointer: \t" << *myPointer << endl;
cout << "myPointer: \t" << myPointer << endl;
cout << "&myPointer: \t" << &myPointer << endl;
cout << "myPointer[0]: \t" << myPointer[0] << endl;
cout << endl;
int myArray[3] = {1,2,3};
cout << "*myArray: \t" << *myArray << endl;
cout << "myArray: \t" << myArray << endl;
cout << "&myArray: \t" << &myArray << endl;
return 0;
}
All of output are exactly what I expected, except last one (&myArray). Lets say my ram something like this:
Address
Variable
Value
0xA100
a
10
0xA101
myPtr
0xA100
0xA102
1
0xA103
2
0xA104
3
0xA105
myArray
0xA102
If I imagine it correctly, then how "&myArray" can be same with "myArray"? Actually, I think it can be anything but 0xA102. Because, this result means that "myArray" is in 0xA102 and value of pointed by myArray is in 0xA102 too. And I know it is weird but it means also, as a value "1", is in 0xA102 too. (At least I got it from this result).
So, I cannot catch the point. I think the result has to be 0xA105 if "&" means address. If yes, why result is not 0xA105. If not, why they have different usage although arrays are pointers.
Is there anybody can clarify the matter?
Thanks.
Related
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 4 years ago.
I'm very new to C++. From examples, I find this use of sizeof in order to retrieve the length of an array
int main()
{
int newdens[10];
// the first line returns 10 which is correct
std::cout << "\nLength of array = " << (sizeof(v1)/sizeof(*v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(v1) << std::endl; //returns 40
std::cout << "\nLength of array = " << (sizeof(*v1)) << std::endl; //returns 4
}
But if i wrote a function like this
#include <iostream>
void myCounter(int v1[])
{
int L, L2, L3;
L = (sizeof(v1)/sizeof(*v1));
L2 = (sizeof(v1));
L3 = (sizeof(*v1));
std::cout << "\nLength of array = " << L << std::endl;
std::cout << "\nLength of array = " << L2 << std::endl;
std::cout << "\nLength of array = " << L3 << std::endl;
}
int main()
{
int v1[10];
std::cout << "\nLength of array = " << (sizeof(v1)/sizeof(*v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(*v1)) << std::endl;
myCounter(v1);
}
the outputs are L=2, L2 = 8, L3 = 4. I can't understand where the problem is.
How to retrieve the correct lenght of v1 inside the function?
Your problem here is that sizeof() is resolved at compile time. As it has no information about how large is your array, it cannot tell its size. It interprets it as a pointer to an int, which is 64-bit on your machine.
The best way for you is to use std::vector instead of C-style array and use its method size().
I've been given a set of different Pointer to Pointer exercises. Each dereferencing an array of pointers. It's definitely challenging and confusing when analyzing them without a compiler. Does anyone have any systematic tricks to solve them?
int main(void)
{
const char* s[] = { "AB", "XY", "EZ"};
const char** z = s;
z += 1;
cout << "The value of **z is: " << **z << endl;
cout << "The value of *z is: " << *z << endl;
cout << "The value of **(z-1) is: " << **(z-1)<< endl;
cout << "The value of *(z-1) is: " << *(z-1)<< endl;
cout << "The value of z[1][1] is: " << z[1][1]<< endl;
cout << "The value of *(*(z+1)+1) is: " << *(*(z+1)+1)<< endl;
return 0;
}
I have another puzzle here, which is definitely a little bit shorter.
int foo[] = {1, 4, 9};
int bar[] = {16, 26, 36, 49};
int main(void){
int *x[2];
x[0] = bar;
x[1] = foo;
*x[1] = (*x)[1];
//What changes?
}
I was able to get the correct results after a while, but I cannot consistently get the correct answers.
I'm looking for a trick similar to reading a function containing "const" right to left. I.e.
const char **x;
"x is a pointer to a char pointer that is constant."
ANSWERS BELOW:
-
-
-
The answers are:
**z is X, *z is XY, **(z-1) is A, *(z-1) is AB, z[1][1] is Z, * ( *(z+1)+1) is Z.
There are no tricks, it's just a matter of understanding the mechanics of each piece of the puzzle. Let's break it down.
z += 1;
z starts at s[0], so now it's s[1].
cout << "The value of **z is: " << **z << endl;
**z is the same as *s[1], which is the same as s[1][0]. Which is 'X'.
cout << "The value of *z is: " << *z << endl;
*z is the same as s[1], which is a char* pointer pointing to XY.
cout << "The value of **(z-1) is: " << **(z-1)<< endl;
**(z-1) is the same as *s[0]. Which is 'A'.
cout << "The value of *(z-1) is: " << *(z-1)<< endl;
By now the pattern should be obvious, this is s[0] which is a pointer to "AB".
cout << "The value of z[1][1] is: " << z[1][1]<< endl;
z[1] is the same as *(z+1); since z is already s+1, that means the expression is the same as *(s+2) or s[2]. Taking an additional subscript from that is indexing into the pointer at s[2], so s[2][1] is the second character of the string or 'Z'.
cout << "The value of *(*(z+1)+1) is: " << *(*(z+1)+1)<< endl;
Working our way from the inside parenthesis out, *(z+1) we've already determined is s[2]. Adding 1 to that pointer gets to the second character just as in the previous example, and dereferencing that pointer with * results in the character 'Z'.
So I don't know if this is the most efficient way of doing it, but the way I understand it is that [] and * are almost interchangeable for pointer to pointers. It's almost like a 2D array. It's just that [] has a higher precedence than *.
Therefore, looking at **z, we can analyze it as z[0][0]. For a more challenging example, we can analyze **(z-1) as z[-1][0]. Finally, the most challenging, *(*(z+1)+1) can be analyzed as z[+1][+1].
This question already has answers here:
Why is address of char data not displayed?
(8 answers)
Closed 6 years ago.
After printing a pointer to an int, I print a pointer to a char:
#include <iostream>
using namespace std;
int main() {
int i;
cout << "&i: " << &i << endl;
char q = 'q';
cout << "&q: " << &q << endl;
return 0;
}
I get the following output as expected:
&i: 0xffffcc0c
&q: q
However, if I comment out cout << "&i: " << &i << endl;, and run the program again, I get the following unexplained output:
&q: q����
Does anyone know why this is happening?
If it has to do with operator<< inserting into the stream until it finds a null character, then why do I get the expected output when I include cout << "&i: " << &i << endl;?
NOTE: I am not expecting to get the address of q from cout. I am expecting to get the C string pointed to by &q. What bugs me is how the output just prints the 'q' if I include the line cout << "&i: " << &i << endl; beforehand. However, if I comment that line out, there is garbage data in the output. Why is there not garbage data in my output when I include the line cout << "&i: " << &i << endl;?
The bit &q thinks it is a string.
Therefore will print up to the null character. hence the extra output
So while studying for my exams I was trying to do a practice problem for pointers.
In the following code I'm trying to display the number of elements before the first occurrence of 0.
There is only one part that i didn't understand please see the 6th last line.
#include <iostream>
using namespace std;
int main()
{
int A[10];
for (int i = 0; i < 10; i++){
cout << "Please enter number " << i + 1 << " in the array: ";
cin >> A[i];
}
int *Aptr = A;
while(*Aptr !=0){
cout << *Aptr << "";
Aptr++;
}
cout << "\nThere are " << (Aptr - A) //Here is what i don't understand.
<< " numbers before the first occurrence of 0." << endl;
system("pause");
return 0;
}
So why exactly is (Aptr - A) giving me the number of elements instead of a memory location, and why is this even doable since Aptr is a pointer and A is an array?
Can someone explain to me in detail?
When used in an expression, like Aptr - A, the name of an array A will be implicitly converted to a pointer (equal to &A[0]).
Then the compiler is faced with subtracting two pointers of the same type (both of type int * in your case). That is specified as giving a value of type std::ptrdiff_t, which is, in turn "a signed integral type able to represent the result of subtracting two pointers".
Pointer arithmetic, when subtracting two pointers of type int (i.e. two int *s) gives the number of ints between the two pointers (assuming they are in the same object, which is true in this case, since Aptr points at an element of the array A).
Practically, if Aptr is equal to &A[i], the subtraction Aptr - &A[0] gives a std::ptrdiff_t equal to i.
Note: there is another problem in your code, as since the first (for) loop reads 10 values, while the second while loop keeps incrementing Aptr until it points at an int with value 0. If the user enters any zero values, the second loop will stop when it finds the first (even if the user enters non-zero elements after that). If the user enters no values equal to 0, then the while loop has undefined behaviour, since Aptr will keep walking through memory past the end of A until it happens to find memory that compares (as an int) equal to 0.
First of all, name of array A is associated to address of (pointer at) the first item in the array.
So why exactly is (Aptr - A) giving me the number of elements?
Because according to rules address arithmetic subtraction operation (also +, and similar) is performed based on the data type.
I mean, that compiler operating with int* makes ++, --, addition, subtraction an integer, etc. adds addresses needed for shifting to next/previous item.
If you really want to see how many bytes are located between addresses, just convert addresses to int before making subtraction:
cout << endl << "Address difference is " << int(Aptr) - int(A) << endl;
You can try that with different data types as follows:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int A[5];
short B[5];
unsigned char C[5];
cout << "Array (data type) | Syze of array | Size of item | Item distanse | Bytes distance" << endl;
cout << "A (int) :" << setw(10)
<< sizeof(A) << setw(15)
<< sizeof(A[0]) << setw(15)
<< &A[4] - A << setw(15)
<< int(&A[4]) - int(A) << endl;
cout << "B (short) :" << setw(10)
<< sizeof(B) << setw(15)
<< sizeof(B[0]) << setw(15)
<< &B[4] - B << setw(15)
<< int(&B[4]) - int(B) << endl;
cout << "C (un.char) :" << setw(10)
<< sizeof(C) << setw(15)
<< sizeof(C[0]) << setw(15)
<< &C[4] - C << setw(15)
<< int(&C[4]) - int(C) << endl;
system("pause");
return 0;
}
UPDATE
To be better prepared for your exam, consider the following example with pointers:
#include <iostream>
using namespace std;
int main()
{
int A[5] = {0}; // all items now are 0
int * P = A + 2; // the same as P = &A[2];
*P = 33; // writing to item A[2];
cout << A[2] << endl; // just to check in usual way
cout << *(A + 2) << endl; // using A as a pointer
cout << *(2 + A) << endl; // almost the same to previous
cout << 2[A] << endl; // quite strange, but it works
cout << 0[P] << endl; // and this is the same
return 0;
}
You must understand that 0[P] means for compiler *(0 + P), as well as 2[A] means - *(2 + A), but you should not write in your program in such style (exceptions are only cases when you want to confuse a reader).
And one more important thing - difference between array and pointer - are shown in the following example:
int A[] = {1, 2, 3, 4, 5};
int *P = A;
cout << "A = " << A << endl;
cout << "P = " << P << endl;
cout << "size of A = " << sizeof(A) << endl;
cout << "size of P = " << sizeof(P) << endl;
even if the addresses (vaules A and P) are equal, compiler works with array (A) in a different way than with pointer: sizeof(A) means memory allocated for whole array (5 items of sizeof(int) each), but sizeof(P) means memory allocated for data type int * (pointer to int). So, sizeof(P) depends only on compiler and OS platform (e.g. pointer can be 32-bit or 64-bit), but sizeof(A) depends on size of item (int may be not 32 bits) and NUMBER OF ITEMS in the array.
And you can "go to the next item" with pointer:
P++;
cout << *P << endl;
but you are not able to do:
A++;
because A is not variable of pointer type (it is just similar in sense of "address of the first item"), and compiler will say you something like:
error : '++' needs l-value
I was trying to find the memory address of an array elements but the output is turning out to be in Hexadecimal. I would appreciate if u could tell me how to convert it to a Decimal output.
Here is the Code,
#include<iostream>
using namespace std;
int main()
{
int a[4];
cout << "Address of a[0] = " << &a << endl;
cout << "Address of a[1] = " << &a[1] << endl;
cout << "Address of a[2] = " << &a[2] << endl;
cout << "Address of a[3] = " << &a[3] << endl;
cin.get();
return 0;
}
In C++11 you can cast to uintptr_t, like
cout << "Address of a[0] = " << static_cast<uintptr_t>(&a) << endl;
The type uintptr_t is specifically designed to represent any possible pointer, so the solution is portable.
I am not aware of a portable solution in C++98/03, although a cast to size_t often (but not always) works. Related: Converting a pointer into an integer.
EDIT
Looking at http://en.cppreference.com/w/cpp/types/integer and also at the C++ standard 18.4.1 Header <cstdint> synopsis [cstdint.syn], it looks like uintptr_t is optional. I have no idea whether there is an implementation that does not define it, and why would one chose to not define it. Any comments are welcome.