Mohsen Sarkar
Mohsen Sarkar

Reputation: 6040

How to change address of a static array variable in C++?

Let's assume we have defined a variable like this :

static struct array myVar;
// &myVar is 0x100

Is it possible to change it's address without touching it's declaration ?
Too be more clear I don't want to declare it as pointer.

// &myVar should be != 0x100

Upvotes: 0

Views: 433

Answers (4)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361672

In the comment you said :

Well, I'm asking this because while I was debugging a C++ program I saw visual studio to show different addresses at runtime with &myVar

If you have declared myVar in .h file which you have included in multiple .cpp file, then in each .cpp file you will see different address of myVar. It is because myVar has internal linkage as it is declared static. Internal linkage means each translation unit (.cpp file) will have different definition of the variable. So if there are N .cpp files, there are basically N version of myVar each with different address. That is one possible explanation!

The fix is this:

  • Declare the variable as extern instead of static in the .h file:

     //file.h
     extern struct array myVar; //it is just a declaration
    
  • Then in exactly one .cpp file, define it, without static keyword:

     //anyfile.cpp
     struct array myVar; //it is a definition!
    

Upvotes: 3

Mats Petersson
Mats Petersson

Reputation: 129494

It does depend on the compiler/linker environment that you are using. This would be entirely outside the C or C++ standards, but some (if not most) compilers allow you to assign the "section" (or something similar) that the data or code ends up in, and then you can tell the linker what address.

But that's probably not what is happening in a visual studio compile without a lot of effort.

Upvotes: 0

NPE
NPE

Reputation: 500773

No, it is not possible to change the address of myVar at runtime.

I'm asking this because while I was debugging a C++ program I saw visual studio to show different addresses at runtime with &myVar

myVar could well be assigned different addresses during different runs of your program.

If the address is changing during the same run, the two most likely explanations are:

  • you have more than one myVar;
  • the debugger is not displaying the address correctly.

Upvotes: 2

bash.d
bash.d

Reputation: 13207

When you compile your program, the compiler replaces the symbol myVar with an address in memory. All addresses are assigned either at compile time, like with your struct or at runtime, when using dynamic memory with the new-operator. So it is not possible to change the address of the variable, it would be catastrophic if you could do.

Upvotes: 0

Related Questions