Search code examples
c++classrandomstructletters

Random letters in C++ struct


So I have a structure I'm making, which I can also make a class, but when I try to get the properties of them...it gives me random letters. Like completely random. I'm seeing stuff like "(▌ ¶∞♥!¶↑♥!¶≤    ≈ ¶⌠  ☻!¶≈   Ç┌ ¶√   Φ`◄¶ ◄▬¶Ç┌ ¶√   Ç☻V♫√   ╨┘ ¶⌠   ╨┘ ¶⌠   0│".

I've trimmed it down to something completely basic, and I'm still clueless as to why it's doing this.

struct Example
{
    const char* Whatever = "Hello";
};

And when I do this

Example* exampleObj;
print(exampleObj->Whatever);

It brings up the random letters. The random letters vary from execution to execution of the program.


Solution

  • A pointer is a variable that holds the address in memory were an object resides. So declaring a pointer is not enough, you also need to create something for it to point at. That means you need to set aside some memory in-which you can put your object.

    Example* exampleObj; // at the moment exampleObj contains spurious data
    

    That is just a pointer. But you have not created anything for it to point at. If you try accessing it you are accessing spurious garbage!

    So to allocate a chunk of memory containing a valid object you need to use new like this:

    Example* exampleObj = new Example; // new returns a chunk of valid memory
    

    Now the pointer is assigned a valid memory address that contains the object you just created using new.

    NOTE:

    There is often no need to allocate your objects manually using new. Instead you can use an automatic variable rather than a pointer:

    Example exampleObj; // note no * means its not a pointer but a whole object
    

    SOLUTION:

    So we have 2 ways to solve your problem. Create a new object and assign its address to your pointer or create an automatic object:

    // Solution 1:
    Example* exampleObj = new Example; // Must remember to delete (smart pointer?)
    print(exampleObj->Whatever);
    
    // Solution 2 (usually MUCH better)
    Example exampleObj;
    print(exampleObj.Whatever); // note: uses . rather than ->