I have a function that returns the first n characters until a specified character is reached. I want to pass a ptr to be set to the next word in the string; how do I accomplish this? Here is my current code.
char* extract_word(char* ptrToNext, char* line, char parseChar)
// gets a substring from line till a space is found
// POST: word is returned as the first n characters read until parseChar occurs in line
// FCTVAL == a ptr to the next word in line
{
int i = 0;
while(line[i] != parseChar && line[i] != '\0' && line[i] != '\n')
{
i++;
}
printf("line + i + 1: %c\n", *(line + i + 1)); //testing and debugging
ptrToNext = (line + i + 1); // HELP ME WITH THIS! I know when the function returns
// ptrToNext will have a garbage value because local
// variables are declared on the stack
char* temp = malloc(i + 1);
for(int j = 0; j < i; j++)
{
temp[j] = line[j];
}
temp[i+1] = '\0';
char* word = strdup(temp);
return word;
}
You’d pass an argument that is a pointer to pointer to char; then in the function, you can change the value of the pointed-to pointer. In other words
And inside your function…