I am new to C++. For a school project I need to make a function which will be able to return a string array.
Currently I have this in my header:
Config.h
Try this
#include
#include
using namespace std;
string * essai()
{
string * test = new string[6];
test[0] = "test0";
test[1] = "test1";
test[2] = "test2";
test[3] = "test3";
test[4] = "test4";
cout<<"test et *test\t"<<&test<<' '<<*(&test)<<'\n';
return test;
}
main()
{
string * toto;
cout<<"toto et *toto\t"<<&toto<<' '<<*(&toto)<<'\n';
toto = essai();
cout<<"**toto\t"<<*(*(&toto))<<'\n';
cout<<"toto\t"<<&toto<<' '<<*(&toto)<<'\n';
for(int i=0; i<6 ; i++)
{
cout<
For example, in my computer, the result is
toto et *toto 0x7ffe3a3a31b0 0x55dec837ae20
test et *test 0x7ffe3a3a3178 0x55dec9ffffd038
**toto test0
toto 0x7ffe3a3a31b0 0x55dec9ffffd038
test0 0x55dec9ffffd038
test1 0x55dec9ffffd058
test2 0x55dec9ffffd078
test3 0x55dec9ffffd098
test4 0x55dec9ffffd0b8
0x55dec9ffffd0d8
Getting addresses and contents of addresses could help you to understand that an array in c++ is really rudimentary : it offers no methods and you could access an index without allocating memory (the value 6 in the loop). Your first example show a direct allocation of a local array (test), so you can't return it (the local array dies), in this example, the local variable dies also but there is always a variable that access at this part of allocated memory, the function, and then the variable that receive the result of the function, so the variable test is dead after the calling of the function but the memory is still allocated. Regards.