0
How to get address of a dynamically allocated char array ?
About some other ones like char* x = "123" and char x [ ] = { '2', 'a' } I found its legal way to do ( which is (void*) (x) ), but about this one, it was of no avail :( Please help me out, thanks👍 Example : Class A { public : ... char* data () { return &content; // returns address of content // illegal way to get its address // using ampersand } ... private : const int SIZE = 5000; char* content = new char [ SIZE ]; }
12 Answers
+ 3
Yes, you cannot return as void* if the return type is char*.
A some_a;
char* v = some_a.data();
cout << static_cast<void*>(v);
+ 2
I am not sure exactly what you did before with the ampersand so that it worked. The trouble with C++ is that operators can come out of the box overloaded for various types with effects you wouldn't expect. Be sure to be absolutely aware of the type you are dealing with. When you used ampersand before, maybe you had a char** type. That is not char* and so you get a different effect of the << operator...
+ 2
Ani Jona 🕊 I meant this :
char* arr = new char [ 2 ];
arr [ 0 ] = '1';
cout << &arr;
So we see that "cout << &arr;" gives the expected result, but doing the same by RETURNING it doesn't ...
Thank you so much .
+ 2
Well, like I said, arr is char*, hence &arr is char**. While you did get an address, you got the address of the address of the array, not the address of tge array itself. You might want to compare the addresses by also casting arr to void* and print the address.
+ 2
Ani Jona 🕊 I got it, thanks for your help ;)
+ 1
Just "return content;" ?
The type of 'content' is already pointer to char. Ampersanding it makes it char**, which is not the methods return type.
+ 1
It is a pointer. It IS the address.
+ 1
Are you just cout'ing the returned value? If so, cout is overloaded for char*, i suspect, to print the content as C string and not the address.
You can cast to void* before inserting into a stream.
+ 1
Ani Jona 🕊 yes, I don't expect the C string result, but its 'address' .
I tried 'return (void*) (content);', but there raised an error : invalid conversion from void* to char*
+ 1
Ani Jona 🕊 FIXED ! Thanks.
But it's a bit strange to me, cout'ing the array using ampersand perfectly works and gives the expected result, but returning it doesn't, what's the reason ?
0
Ani Jona 🕊 'return content' only returns what it contains, not its address
0
Ani Jona 🕊 well I don't notice anything like 0x97645ba0, but only what it contains. Do you mean that its address is what it contains ??
>> content [ 0 ] = '1';
content [ 1 ] = '2';
>> return content;
// output : 12