I have a function that needs to remove leading whitespace from a string. For some reason, this does not work:
static void remove_leading_spaces(char* line)
{
int i;
for(i = 0; line[i] == ' '; i++); //iterate through till whitespace
line = line + i; // advance the pointer to point to
// the first non space character
}
For example, if I have a string with a single leading whitespace, the string will not be altered.
Thanks everyone the answers are correct for remove_leading_spaces!
How would I do this with a string that needs to be returned from the function that calls this function? I have been trying the same approach and I keep getting a segmentation fault? Is it the same exact concept?
In the function below you are passing the pointer by value.
Which means any change to
linein the body is not reflected in the caller. You need to change your function like this:EDIT
Be careful NOT to free
lineafter this as you would not deallocate the entire string. If the memory was dynamically allocated, you’ll need to keep a backup copy of the original pointer to safely free it.