Reputation: 2484
I was writing a postfix evaluation program which could handle multiple digits. Therefore I first read the inputs to a character array, and split them to array of (character array). Whenever I run my program, it gives a segmentation error (g++ on Ubuntu 13.10)
Here's my function to split
int split(char str[], char *ret[]){
int c=0;
char * pch;
pch = strtok (str," ");
while (pch != NULL)
{
//printf ("%s\n",pch);
strcpy(ret[c], pch); c++;
//cout<<ret[c];
pch = strtok (NULL, " ");
}
return c;
}
And part of my main()
char* s;
s = new char[200];
cout<<"Enter Postfix Expression:\n > ";
cin.getline(s,200);
char* st[200];
//int size=3;
int size = split(s, st); // < Is what I'm passing correct?
I could not understand why the segfault occurred. Any suggestions?
EDIT: Thanks to yugnum for the answer. The following did the trick
...
ret[c] = new char[strlen(pch)];
strcpy(ret[c], pch); c++;
...
Upvotes: 1
Views: 114
Reputation: 5002
You need to define st
as 2D array, so split function will return an array of split strings
For example:
char st[20][200]
and then:
int split(char str[], char *ret[][]){
So you'll have 20 of 200 byte char array.
But it's not safe at all, I suggest you considering something else like vector
or std::string
. Also you need to allocate your array before strcpy
.
Then
strcpy(ret[c], pch);
with c as counter, will copy split new string to your char array. But consider std::string, which is best choice
Upvotes: 0
Reputation: 5684
char* st[200];
int size = split(s, st);
int split(char str[], char *ret[]){
...
strcpy(ret[c], pch);
...
}
this is what is wrong, you just pass bunch of uninitialized pointers to strcpy while it requires pointer that points to valid allocated memory.
Upvotes: 2