-1

I am trying to initializing structs in the following manner below, and then passing it by reference and then trying to retrieve the value. However, i get a random numbers back, which seems to suggest i dont have anything in that address. Why is this happening?

#include <iostream>

using namespace std;

struct newStruct {

int numberOne;
int numberTwo;
int numberThree;

};

newStruct initializer{
 1,2,3

};

 void printStruct(struct newStruct* inputNew) {
  printf("This is the output %d\n", inputNew->numberOne );
 printf("This is the second output %d\n", inputNew->numberTwo);
 printf("This is the third output %d\n", inputNew->numberThree);
}

int main() {

struct newStruct initializer;


printStruct(&initializer);
getchar();
} 

1 Answers1

2
int main() {
    struct newStruct initializer;

Here you are defining a local, uninitialized variable of type newStruct called initializer; it has nothing to do with the global variable called initializer that you defined above, and, having the same name, the local actually hides the global (when you perform an unqualified name lookup).

To access the global variable just avoid defining a local with the same name.

int main() {
    printStruct(&initializer);

You can also refer to a hidden global by explicitly qualifying it with the scope resolution operator (as in, ::initializer), but I don't think that's what you are after here.


By the way, this being C++ and not C you don't have to prefix newStruct with the struct keyword when you refer to the type name.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299