struct args
{
char command[64];
char args[2][64];
};
int argscount = 0;
struct args* arguments;
int buffersize = 64;
char *ptoken = NULL;
char input[buffersize];
char *pstr = NULL;
int a = read(0,input,buffersize);
pstr = input;
arguments = malloc(sizeof(struct args));
if(a>0){
ptoken = strtok(&pstr," ");
strcpy(arguments->command,ptoken);
printf("TOKEN:%s\n", ptoken);
while( ptoken != NULL ) {
if(argscount > 1){break;}
ptoken = strtok(NULL, ' ');
strcpy(arguments->args[argscount],ptoken);
argscount++;
}
}发布于 2013-10-26 08:45:01
问题最有可能出现在
ptoken = strtok(&pstr," ");strtok的第一个参数应该是
char *您可以将其作为
char **发布于 2013-10-26 08:37:51
正如strtok所期望的那样,read不会返回以null结尾的字符串。您将需要在输入中分配一个额外的字节来添加'\0'。您可以查看read的返回值来查看读取了多少字节,然后将'\0'放在input[a]处。
int a = read(0,input,buffersize-1);
input[a] = '\0';发布于 2013-10-26 08:59:19
代码中的几个修复(和其他)。注释描述了我所做的更改:(如果定义了read()函数,它可能已经构建)还添加了main,只是为了通过错误进行编译。
#include <ansi_c.h>
struct args
{
char command[64];
char args[2][64];
};
int argscount = 0;
struct args* arguments;
size_t buffersize = 64; //changed to size_t
char *ptoken = NULL;
char input[64]; //variable initializer not allowed, changed
char *pstr = NULL;
int read(int a, char *s, size_t size);
main(void)
{
int a = read(0,input,buffersize);
pstr = input;
arguments = malloc(sizeof(struct args));
if(a>0)
{
ptoken = strtok(pstr," "); //changed &pstr to pstr
strcpy(arguments->command,ptoken);
printf("TOKEN:%s\n", ptoken);
while( ptoken != NULL ) {
if(argscount > 1){break;}
ptoken = strtok(NULL, " "); //changed ' ' to " "
strcpy(arguments->args[argscount],ptoken);
argscount++;
}
}
}https://stackoverflow.com/questions/19601495
复制相似问题