taking input of pointer to char in struct

I am facing problem in taking input for pointer to char.Program compiles without any error but while running it gives error when I hit enter after first loop of input for name.
What's wrong with this code ?

error is unhandled exception.Access voilation writing location

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
29
30
31
32
33
  #include <iostream>

using std::cout;
using std::endl;
using std::cin;

struct employee{
	int x;
	char *name;
};


int _tmain(int argc, _TCHAR* argv[])
{

	const int array_size=2;
	employee e[array_size];
	
       for(int i=0;i<array_size;i++){
	cin >> e[i].x;
	cin >> e[i].name;			//error
	//e[i].name="Hello World";	//works well
	}

	for(int i=0;i<array_size;i++){
		cout << e[i].x << endl;
		cout << e[i].name << endl;
	}
	
	return 0;
}

closed account (SECMoG1T)
I guess you must provide the size of a static array on declaration .

1
2
char *name// you could provide the size here /*char name [2]*/
cin>> e [i].name; /// is an error coz you are trying to access some memory you dint allocate to your array  

Last edited on
why e[i].name = "Hello world!"; works
consider an array
1
2
3
4
char string[] = "Hello world"; //string is a pointer to the first element ('H');
char *pointer_to_char;  
//since it is proper to assign pointers to another, then you can do..
pointer_to_char = string; //This is thus the same as pointer_to_char = "Hello Word"; 


Why cin>>e[i].name does not work
1
2
3
4
5
6
7
char *pointer; //this is not a variable that can store user input data.
                      //it can only hold the address of the data in memory
                      //so doing cin>>pointer is wrong. ( cin>>e[i]);
//what you want to do is create memory for the name you want to input
//then assign the address of the memeory location to pointer.

pointer = new char [SIZE_OF_STRING];
Topic archived. No new replies allowed.