My code:
#include <iostream>
using namespace std;
int main() {
char *test = (char*)malloc(sizeof(char)*9);
test = "testArry";
cout << &test << " | " << test << endl;
test++;
cout << &test << " | " << test << endl;
return 1;
}
Result:
004FF804 | testArry
004FF804 | estArry
I don't understand how it's possible that I had moved my array pointer and address didn't change.
The pointer did change. You're just not printing it. To print the pointer test
:
cout << (void*) test << endl;
&test
is the memory location where test
is stored.test
is the value that you incremented with test++
(i.e., you didn't increment &test
).
When you do cout << test
the overload of operator<<
that gets picked is one that takes a const char*
and treats it as a C-style string, printing the characters it points to. The cast to void*
avoids this behavior in order to print the actual value of test
, instead of the value it points to.
In this statement
cout << &test << " | " << test << endl;
expression &test
yields the address of the variable test
itself that is evidently is not changed. It is the value stored in the variable was changed.
If you want to output the value of the variable test
that is the value that points inside the string literal you should write
cout << ( void * )test << " | " << test << endl;
Take into account that there is a memory leak in the program because after allocating memory the pointer is reassigned. And sting literals have types of constant character arrays. So the pointer test should be declared like
const char *test;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With