Re: How to Return an array of strings in C (char**)
- From: "Malcolm McLean" <regniztar@xxxxxxxxxxxxxx>
- Date: Sun, 25 Mar 2007 19:04:00 +0100
<vignesh4u@xxxxxxxxx> wrote in message
I am trying to implement the Split function in C ie.This must be where you crashed, if you cut and pasted this code. The input must be null or not set up correctly.
if i have a string: char* S="This is a test";
and if i try to split based on space ' ' it should return an array of
strings like:
{"This","is","a","test"} .
I tried to implement it as given below but am getting a segmentation
fault. I would really appreciate if some one could give me an answer
on this issue:
char** split(char str[],int*c) {
int start=0;
int end =0 ;
char** temp=NULL;
char** ptr;
int count=0;
int length = strlen(str);
//first counting the number of spaces
// to know the number of elements in the array
while (str) {
if (*str==' ') count++;
}
The reason is that you fail to increment str. Unless input is an empty string, this will run forever. Since the program didn't hang, probably the crash was above.
you want (count + 1) * sizeof(char *).
printf("count value is %d \n",count);
// I am doubt ful about the malloc too
ptr = (char**) malloc(sizeof(char)*(count+1));
It is an array of pointers, not of chars.
*ptr = str + start.
*c = count+1;
while(end<length) {
ptr = str + start;What is length doing in this condition ?
if (str[end]!=' ' || length) {this should surely be an else if.
end++;
}
if (str[end]!='\0') {// replacing spaces with \0
str[end]='\0';
Now you need to set *ptr to str + start. You also need to update start, and increment end.
{This confused me. Much better to set temp before entering the loop.
if (!temp) temp= ptr;
ptr++;
}
return temp;
}
Thanks
Its nearly there. Generally the way to debug rotuintes like this is to slip in diagnostic printfs. For instance you could have printfed your input printf("***%s***\n", str) to see it was valid. The asterisks are there to pick up any funny spaces. The you could have printed "here" before entering the main loop to see if you actually got there, then str + start to see where you go to in the string on each pass.
.
- References:
- How to Return an array of strings in C (char**)
- From: vignesh4u
- How to Return an array of strings in C (char**)
- Prev by Date: Re: feof(), fseek(), fread()
- Next by Date: Re: Copying Structures
- Previous by thread: Re: How to Return an array of strings in C (char**)
- Next by thread: Re: How to Return an array of strings in C (char**)
- Index(es):
Relevant Pages
|