You don't increment j
, ever. In the case that the current character of the source string is not a space, you probably would like to store it in your output string and then also increment the j
by one; so that you'd store the next possible character into the next slot instead of overwriting the 0
th one again and again.
So change this:
...
withoutSpace[j] = helpArr[i];
...
into this:
...
withoutSpace[j++] = helpArr[i];
...
And then also append your withoutSpace
with a 0
or '\0'
(they are the same), so that any string processing function may know its end. Also return the pointer, since you should do that, not the *withoutSpace
or withoutSpace[0]
(they are the same):
char *ignoreSpace( char helpArr[], int length ){
int i = 0; int j = 0;
char * withoutSpace = malloc( length * sizeof * withoutSpace ); // <-- changed this
while ( i < length ){
/*if not a space*/
if ( isspace( helpArr[i] ) == FALSE )
withoutSpace[j++] = helpArr[i]; // <-- replaced j with j++
i++;
}
withoutSpace[j] = 0; // <-- added this
return withoutSpace;
}
And then you should be good to go, assuming that you can have variable-length arrays.
Edit: Well, variable-length arrays or not, you better just use dynamic memory allocation by using malloc
or calloc
or something, because else, as per comments, you'd be returning a local pointer variable. Of course, this requires you to manually free
the allocated memory in the end.