Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving array pointer isn't changing ADDRESS of start

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.

like image 556
Yas Avatar asked Dec 24 '22 20:12

Yas


2 Answers

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.

like image 110
emlai Avatar answered Jan 05 '23 10:01

emlai


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;
like image 33
Vlad from Moscow Avatar answered Jan 05 '23 11:01

Vlad from Moscow