Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vector of an array of structs resets strings to be blank. C++

So I’m having a very confusing issue where I’m attempting to print a string from a vector of arrays of structs to the console. Integers print just fine however strings stored within these structs get set to "". I have no idea what’s going on here but after setting up a test as shown bellow this issue is still persisting. Any help figuring this out would be greatly apricated.

Should also mention I’m still new to c++ so I apologise if the issue here is something simple.

#include <iostream>
#include <string>
#include <vector>
#include "Header.h"

//Test struct
struct testStruct
{
    string testString;
    int testInt;
};

testStruct testArray[1] = {
    testArray[0] = {"String works", 69}
};

int main()
{
    srand(time(NULL));
    
    vector < testStruct > test;
    test.push_back({ testArray[0] });
    cout << test[0].testString << "\n"; // prints "", should print "String works"
    cout << test[0].testInt << "\n"; // prints 69
    
    characterCreation();
    checkPlayerStats();
    introduction();

    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This surprised me. The following code is legal (syntactically at least)

testStruct testArray[1] = {
    testArray[0] = {"String works", 69}
};

but if you replace it with the sensible version

testStruct testArray[1] = {
    {"String works", 69}
};

then your program works as expected.

I expect your version has undefined behaviour because you are assigning (here testArray[0] = ...) to an array element that has not yet been created.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading