error: acces violation

Guys,

I've a little problem with a little program and I can't figure out what the problem is and how to solve it.
Purpose of the program:
open a .csv file
read a line
split the string (delimiter = ; ) and store the substrings.

Sounds easy, however: it won't run, it doesn't give errors and while debugging it says:
Unhandled exception at 0x102aece9 in LetsTest.exe: 0xC0000005: Access violation writing location 0x00000000.
when jumping to strcpy().

Who can help me? It's a subfunction of a bigger project with a deadline way too soon!
Thank you very much,

poema.

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
int main()
{
	int nrOfTypes=3;
	char* reads[3];
	char delims[]=";";
	string csvfile="sensorData.csv";
	
	//open&read file
	ifstream myfile;
	myfile.open(csvfile.c_str());
	char* id=NULL;
	char* time=NULL;
	char* s=NULL;
	char* copy=NULL;
	string line;
	while (!myfile.eof())
	{
		getline( myfile,line);
		strcpy( copy,  line.c_str()); 
		id=strtok(copy,delims);
		printf( "result %s \n", id);
		time=strtok(NULL,delims);
		printf( "result %s \n", time);
		for(int i=0;i<nrOfTypes;i++)
		{
			reads[i]=strtok(NULL,delims);
			printf( "result %s \n", reads[i]);
		}
	}
	myfile.close();
	return 0;
}


ps: the .csv file is filled with this kind of strings: "1;18/03/2008 11:55;20;-95;498"
Line 14 and 19 are the problem(s).
in line 14 -
1
2
 char* copy=NULL;
 
you have initialised copy to be a NULL (0) pointer and in line
19 you try copying to it !!!! hence the access violation.

you don't need the strcpy function in line 19 because line.c_str returns a char*.
So change line 19 to copy= (char*)line.c_str(); .
You may need the cast because line.c_str returns a const pointer .

I used a 'C' style cast, but the c++ way copy= const_cast <char*>line.c_str(); maybe the more official way to do it.
Topic archived. No new replies allowed.