0

The getword function I wrote takes in buffered input based off of getchar(). It delimits also by metacharacters. After every call, it moves its pointer to the next word in the inputted buffer string and places the most recent one in the char pointer it takes as a parameter, in this case it is the character array called buffer.

Objective: Using the getword function I wrote, I need to store each returned word/token into consecutive indices of the char*args[] I have set up.

My problem is that I cannot properly load these individual tokens into separate indices of my char *args[]. Instead, it seems to store the most recent word into all indices of args after every pass of the for loop. For example, if I type in:

Hello world, this is a test.

It will store the words into args in this way:

  • pass1: args[0]: Hello
  • pass2: args[0]: world, args[1]: world,
  • pass3: args[0]: this args[1]: this args[2]: this

Code:

int main (int argc, char *argv[]) {

    char buffer[MAXBUF], *args[MAXITEM];
    int c = 1;

    for (i = 0; c > 0; i++) {
        c = getword(buffer);
        args[i] = buffer;
        int g = 0;
        while(args[g] != NULL) {
            printf("args[%d]: %s\n", g, args[g]);
            g++;
        }
    }
}
2
  • 3
    You realize you're using, and referencing, the same buffer for all the args, right? I.e as soon as you read the next arg, it overwrites the last one. Look at args in a debugger, and you'll see each, args[0], args[1], etc.. are storing the same address. Commented Nov 17, 2013 at 2:00
  • You should post your code for getword(). Commented Nov 17, 2013 at 2:21

1 Answer 1

1

Try changing

    args[i] = buffer;

to

    args[i] = strdup(buffer);

and see what happens. The study what strdup() does.

Sign up to request clarification or add additional context in comments.

1 Comment

I understand now that I was passing it an address to the same buffer that was getting reused over and over instead of a new string. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.