0

下面是一个用于在执行标记化的程序中获取下一个标记的函数。它目前正在运行,但我仍然不确定它是否符合我教授的要求。如果您查看顶部评论部分,他说“应该动态分配返回令牌的空间”。

每当我听说我希望我必须使用malloc时,但我没有使用malloc就做到了。我这样想对吗?

/*
 * TKGetNextToken returns the next token from the token stream as a
 * character string.  Space for the returned token should be dynamically
 * allocated.  The caller is responsible for freeing the space once it is
 * no longer needed.
 *
 * If the function succeeds, it returns a C string (delimited by '\0')
 * containing the token.  Else it returns 0.
 *
 * You need to fill in this function as part of your implementation.
 */
char *TKGetNextToken(TokenizerT *tk) {
char *sPtr, *tPtr, *delim, *temp = NULL, *ret = NULL;

sPtr = tk->sepr; //pointer to the separators

tPtr = tk->ts;
temp = tPtr;

while (tPtr[0] != '\0') //Scan tokenstream
{
    delim = tk->sepr;
    while (delim[0] != '\0') //scan separator stream 
    {
        if (*tPtr == *delim) //Matched with a separator
        {
            if (tPtr == temp) //Check if beginning of the tokenstream
            {
                //then skip over this character.
                temp++;
                break; //Break loop because it may skip checking a char with a prev delim.
            }
            else
            {
                //Cut off current position with null character and pass over it.
                *tPtr = '\0';
                tPtr++;

                if((ret = malloc(sizeof temp) + 1 * sizeof(char)) != NULL) //add 1 for null character '\0'
                    strcpy(ret, temp);

                tk->ts = tPtr; //In position for next token.

                return ret;
            }
        }
        else
        {
            delim++; //Go to next separator.
        }

    }

    tPtr++; //Go to next character.
    count++;
}

if((ret = malloc(sizeof temp) + 1 * sizeof(char)) != NULL) //add 1 for null character '\0'
    strcpy(ret, temp);

tk->ts = tPtr;
return ret;
}

编辑:所以我想我修复了它,但很好奇,像我一样使用 malloc ,这不是只为指针地址而不是整个令牌分配空间吗?

4

1 回答 1

2

这是一种可能的实施方式,但不是您的教授要求的实施方式。您的教授希望您分配内存并将令牌复制到其中,然后返回指向该分配内存的指针。

于 2012-09-19T04:56:02.863 回答