我的 getToken 函数在第一次调用时不起作用

My getToken function doesn't work on the first call

我为我在学校做的家庭作业编写了这个函数:

char* getToken(char buffer[], int pos)
{
    int i; 
    char copy[350], *token, *del = ",\n"; 

    strcpy(copy, buffer); 
    token = strtok(copy, del); 

    for (i = 1; i < pos; i++) 
        token = strtok(NULL, del); 

    return token; 
}

我希望它在给定位置 return 标记而不破坏原始字符数组。问题是它在第一次调用时 return 垃圾,但它在所有后续调用中都按预期工作。这应该是一个非常简单的修复,但我整天都在编码,我需要一双全新的眼睛来支持我。 (硬编码的 350 是本作业中给出的,缓冲区不应超过 349 个字符)

您正在返回指向非静态局部变量的指针,该变量将在从函数返回时消失并且取消引用从调用者返回的指针将调用未定义的行为

我猜你应该在返回之前复制令牌。添加 #include <stdlib.h> 以使用 malloc()free().

char* getToken(const char buffer[], int pos)
{
    int i; 
    char *copy, *token, *ret, *del = ",\n"; 

    copy = malloc(strlen(buffer) + 1); /* for string longer than 349 bytes is passed */
    if (copy == NULL) return NULL;
    strcpy(copy, buffer); 
    token = strtok(copy, del); 

    for (i = 1; i < pos; i++) 
        token = strtok(NULL, del); 

    ret = malloc(strlen(token) + 1);
    if (ret != NULL) strcpy(ret, token); /* copy string before freeing it */
    free(copy); /* if you use malloc(), use free() */
    return ret;
}