String array problem

Hello, here's the problem...
/*PROBLEMS ARE IN COMMENTS*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
using namespace std;

int main () {
	char** test = new char* [5];
	short i = 0; 
	while (i < 5) {
		char answer [20];
		cout << "enter some string: ";
		cin >> answer;
		short a = strlen (answer);
		test [i] = new char [a];
		test [i] = answer;
		i++ ;
	}
	for (short x = 0; x < 5; x++) 
		cout << test [x] << endl; /* here x is changing but uotput
 is allways same (first string printed 5 times on my console) */


	for (short y = 0; y < 5; y++) /* here ocurs another problem: program CHRASH */
		delete test [y];
	delete [] test;

	system ("pause");
		return 0;
}
test [i] = answer; this makes char* test[i] point to a local variable array answer. Whet you wanted to do is copy the characters and not the pointer. Use strcpy, memcpy or std::copy for that. Also, strlen does not count the null char, so you need to allocate strlen(answer)+1 chars instead.
I'm realy n00b while assigning with local pointer lol;
THANKS for help hamsterman!
Topic archived. No new replies allowed.