2

This is the warning I am getting:

passing argument 1 of ‘strtok’ discards ‘const’ qualifier from pointer target 
type [enabled by default]

I wanted to disable this default operation can anyone help me with this?

Thank you!

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Kyoichi Shido
  • 109
  • 1
  • 8
  • It would be helpful if you show us code which triggers the error with some context. Check [How To Ask](https://stackoverflow.com/help/how-to-ask) – myaut Sep 10 '17 at 10:28

1 Answers1

4

strtok works in-place: it needs to tokenize the string you passed to it.

Of course, you could force non-const cast but that would violate the contract. What if the caller expects to re-use the passed string after your operation? So it's a no-go.

So if you have some constant string, you have to make a copy before using it, for instance using strdup

char *copy = strdup(my_const_char);
toks = strtok(copy," ",NULL);
...

In the end, you have all your tokens in separate pointers, with memory already allocated and held by copy. Once you don't need the tokens anymore, freeing copy is all that you need to clean it up.

Note that a generic answer to this const qualifier question is: Passing Argument 1 discards qualifiers from pointer target type

Steve Summit
  • 45,437
  • 7
  • 70
  • 103
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219