1

我正在制作一个小程序,其中用户键入“print 1 2”或“open file1”之类的命令,为了处理用户想要做的事情,我试图在每个空间使用strtok. 我的问题是以下代码:

void tokenize(char string[100],char tokenized[10][MAX_CHARS]){
    char delims[] = " ";        /*Delimitere is a space so tokenize when a space occurs*/
    char *result = NULL;
    int count = 0;
    result=strtok(string,delims);   /*Tokenize the string*/
    while(result!=NULL && count<10){
        tokenized[count++][MAX_CHARS] = result;  /* This is where I get the error */
        result= strtok(NULL,delims);
    }
}

我收到此错误:

stringapi.c: In function ‘tokenize’:
stringapi.c:33:33: warning: assignment makes integer from pointer without a cast [enabled by default]

我一直试图解决这个问题一段时间没有运气。
我试过tokenized[count++] = result;了,但这给了我以下错误:

stringapi.c:33:22: error: incompatible types when assigning to type ‘char[80]’ from type ‘char *’

我的最终目标是,如果用户键入“open newfile.txt”,我想要一个 array[0]打开的数组,并且array[1]是 newfile.txt,然后我可以相应地处理。

4

3 回答 3

5

以下行:

tokenized[count++] = result;

尝试分配给一个字符数组。你不能这样做,你必须使用strncpy()

strncpy(tokenized[count++], result, MAX_CHARS);

最后,我建议您更strtok_r()喜欢strtok().

于 2012-06-17T11:06:44.340 回答
0

您需要使用strcpy(或更好strncpy)来复制字符串。否则,您只是将指针分配给数组。

于 2012-06-17T11:08:16.770 回答
0

你混淆了两种方法。一种方法是将输入字符串中的所有内容复制到解析版本的不同位置。一种方法是解析后的版本只是一堆指向保存原始输入字符串内存的内存的指针。那条tokenized[...] = result线试图做第二种方法;您使用的数据结构表示第一种方法。

如果您想使用第一种方法,请执行 strncpy 而不是仅分配给标记化的。如果要使用第二种方法,请将 tokenized 更改为 char* 数组。

我会推荐第一种方法,因为它是值得的。

于 2012-06-17T11:09:22.897 回答