I know it's not "best practice" returning pointers to local variables, but in this case I think i need it.
I'm writing a method to remove some characters at the beginning and some at the end of a string and return the result as a pointer to memory allocated in the function.
I developed the function separately, it worked, but when implemented with the rest of the code it doesn't return anything... It seems that the letters is added to the var new, but when i try printing the string, nothing is returned....
The str[] comes from
Hope someone is able to point me in the right direction...
Thanks in advance!
I'm writing a method to remove some characters at the beginning and some at the end of a string and return the result as a pointer to memory allocated in the function.
I developed the function separately, it worked, but when implemented with the rest of the code it doesn't return anything... It seems that the letters is added to the var new, but when i try printing the string, nothing is returned....
Code:
char * prepareMessage(char str[]) {
int i=0, j=0, state=0;
while(str[i]==' ') { i++; } //skip whitespace
while(state == 0 && str[i]!='\0') { //find the start of the message (after 'new ')
if(str[i]=='n' && str[i+1]=='e' && str[i+2]=='w' && str[i+3]==' ') {
state = 1;
i += 4;
}
i++;
}
char * new = malloc(strlen(str)-i);
while(str[i]!='\0') { //copy the chars to the new var
*(new+j) = str[i++];
j++;
}
if(*(new+j-1)=='\"') { //remove trailing " and append \0
*(new+j-1) = '\0';
} else { //no trailing " - something wrong, free mem and return NULL
free(new);
return NULL;
debug("ERROR: NO TRAILING \"");
}
return new;
}
Code:
char inputBuffer[200] = ""; fgets(inputBuffer, 200, stdin)
Thanks in advance!
Comment