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;
}
>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.