1

I used strtok to tokenize an array. I wanted to store the char pointer, that strtok returns, into an array.

  char exp[] = {"1000 + 1000"};
  char operands[50];
  p = strtok(exp, " ");

Now I wanted to store the value of p (that is 1000) into the operands[i] array. I tried it like this:

memcpy(&operands[i], p, 49);

But it only copies a single integer.

5
  • 1
    Is this really C++ ? Why 49 as the last arg of memcpy ? Commented Aug 12, 2014 at 6:48
  • strcpy(operands, p)? Commented Aug 12, 2014 at 6:48
  • 1
    std::string is your friend. Commented Aug 12, 2014 at 6:49
  • "But it only copies a single integer." - that's what strtok does - put a NUL character in to exp[] after the first token, such that your memcpy (which has undefined behaviour because 49 is way larger than sizeof exp) copies "1000\0+ 1000\0" and about 40 other garbage characters. Listen to Bathsjeba - if you use std::string you're less likely to screw up, and if you do you've a somewhat better chance to get the wrong string output instead of crashing your program. Commented Aug 12, 2014 at 6:53
  • I started programming in c, so thats why I still used a c function. (I see the 49, but won't make a difference in this case.) Commented Aug 12, 2014 at 6:55

2 Answers 2

3

I'm guessing you don't actually want to copy the string pointed to by p into the array of characters operands. Instead it seems to me that you want operands to be an array of pointers to char, i.e.

char *operands[50];

Then you can just do

operands[i] = p;

(Note: i have to be a valid index, in the range 0 <= i < 50)


However, the above is a C solution to a C problem. If you're programming in C++ you should probably use std::string and std::vector instead:

std::vector<std::string> operands;

...

operands.push_back(p);

Of course, if you're programming in C++ you should not use character arrays and strtok at all, but use the functionality in the C++ standard library for the tokenizing as well.

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

Comments

0
char exp[] = {"1000 + 1000"};
char operand[50];
char* p = strtok(exp, " ");
memcpy(&operand[0], p, 5);

After running above code, in the char array operand,

the first 5 are assigned value

operand[0] = '1' operand[1] = '0' operand[2] = '0' operand[3] = '0' operand[4] = 0 // end character of char array

others are not assigned value '?'

operand[i] = '?'

Comments

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.