i'm trying to make apt of subject
char test;
char* testPtr = &test;
char** testPPtr;
testPptr = new char* [100];
for (int i = 0; i < 5; i++) {
cin >> testPtr;
testPPtr[i] = testPtr; // math, eng, history, kor, science
}
for (int j = 0; j < 5; j++) {
cout << testPPtr[j] << endl;
}
i think
testPPtr[0] is assigned to math
testPPtr[1] is assigned to eng
testPPtr[2] is assigned to history
However, all double-pointers are assigned the last stored value(science).
Why is this happening?
I tried this code, but I failed.
char test;
char* testPtr = &test;
char** testPPtr;
testPptr = new char* [100];
for (int i = 0; i < 5; i++) {
cin >> testPtr;
testPPtr[i] = new char[100];
testPPtr[i] = testPtr;
}
for (int j = 0; j < 5; j++) {
cout << testPPtr[j] << endl;
}
I'd appreciate any help :)
cin >> testPtr;
has undefined behaviour. It tries to write characters after test
.
Even if you fix that, e.g. by declaring std::string test;
, there is only one string in your program, so all the pointers point to the same place.
std::vector<std::string> subjects(5); // Creates 5 empty strings
for (std::string & subject : subjects)
{
std::cin >> subject; // Read each subject in
}
for (const std::string & subject : subjects)
{
std::cout << subject; // Write each subject out
}