I am trying to return a string array in a function and print the variables of it. I know that there is no way to actually return an array in c++ but you can pass its pointer. So I set up the function to return the pointer value and then print it from there but the pointer is not working. I am getting an exception that it is unable to access reading location.
Exception thrown at 0x7AD2F3BE (ucrtbased.dll) in BankApp__.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
I am using visual studio so when using the debugger I see that its unable to read the contents at that pointer.
string * User::getPersonal() {
string arr[] = { FirstName, LastName, Address, Birthday };
return arr;
}
int main()
User testUser1, testUser2;
testUser1.createLogin("wman", "password", "Wil", "Man", "333 3 Street", "09-03-1997");
testUser2.createLogin("johndoe", "password", "John", "Doe", "123 ABC St.", "12-01-1990");
User users[] = { testUser1, testUser2 };
for (int i = 0; i < sizeof(users) / sizeof(users[0]); i++) {
string * infoArray = users[i].getPersonal();
//cout << *infoArray << endl;
//cout << infoArray << endl;
for (int i = 0; i < 4; i++) {
string fields[] = { "First Name", "Last Name", "Address", "Birthday"};
cout << fields[i] << ": " << *(infoArray + i) << endl;
}
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
}
}
getPersonal()
returns the string array pointer that holds all the data of User
. and then i want to loop through the elements and print them out. Is there a better way to do this?
You're trying to return a pointer pointing to a local (stack allocated) array, which will be destroyed when the function returns and the returned pointer is always dangled.
You can use std::vector
or std::array
instead. e.g.
std::vector<string> User::getPersonal() {
std::vector<string> arr = { FirstName, LastName, Address, Birthday };
return arr;
}
User contributions licensed under CC BY-SA 3.0