I'm trying to extract the words from a string in C and I'm getting unexpected results. I have print statements that seem to confirm my control flow, but printing the final array returns nothing.
In the code below I'm parsing trying to parse input, which is the string "Some stuff \t to parse &". I want to turn that string into params[0] = "Some"; params[1] = "stuff"; params[2] = "to"; params[3] = "parse"; params[4] = "&";
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_PARAMS 10
#define MAX_WORDS 100
void parse(void);
char* input = "Some stuff \t to parse &";
char* params[MAX_PARAMS+1] = {NULL};
int main(int argc, char *argv[]) {
parse();
// Prints nothing!
for (int i = 0; i <= MAX_PARAMS; i++) {
puts(params[i]);
}
}
void parse(void) {
char buffer[MAX_WORDS];
memset(buffer, 0, MAX_WORDS);
int param = 0;
int buff = 0;
int i = 0;
for (; i < strlen(input); i++) {
if (isspace(input[i]) && *buffer) {
printf("Buffer '%s' being added to params[%d]\n", buffer, param);
params[param++] = buffer;
memset(buffer, 0, MAX_WORDS);
buff = 0;
if (param == MAX_PARAMS) {
break;
}
}
else if (!isspace(input[i])) {
buffer[buff++] = input[i];
printf("%c added to buffer\n", input[i]);
}
}
if (param < MAX_PARAMS && strcmp(buffer, "")) {
params[param] = buffer;
printf("Buffer '%s' being added to params[%d]\n", buffer, param);
}
}
strtok(apply copy).params[param++] = buffer;: you set local address.params[param++] = buffer;, the next thing you do is zero out the the buffer withmemset(buffer, 0, MAX_WORDS);so all the saved values are pointing to the same memory, and you keep zapping the memory the words point at to all bytes null. (It's also a local variable, as others have pointed out.) You need to make a copy of the buffer — usestrdup(), implementing it if necessary (it isn't hard to implement).