Copy results of strtok to 2 strings in C

纵然是瞬间 提交于 2019-12-12 23:23:11

问题


Ok, so I have the code

char *token;
char *delimiter = " ";

token = strtok(command, delimiter);

strcpy(command, token);

token = strtok(NULL, delimiter);
strcpy(arguments, token);

and it gives me EXC_BAD_ACCESS when i run it, and yes, command and arguments are already defined.


回答1:


Why are you copying the token into command when you're parsing command? It's a very unsafe thing to do.

You can do:

char *command_tok, *args_tok;

command_tok = strtok(command, delimiter);
args_tok = strtok(NULL, delimiter);

Now command_tok and args_tok point to the command and arguments part of the initial string, assuming it parses correctly. Note that they point to parts of the command buffer and don't have their own allocated memory. You can safely copy from them into other buffers.



来源:https://stackoverflow.com/questions/2523624/copy-results-of-strtok-to-2-strings-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!