简体   繁体   English

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

[英]My getToken function doesn't work on the first call

I've written this function for a homework assignment I'm doing in school:我已经为我在学校做的家庭作业编写了这个函数:

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; 
}

I want it to return a token at a given position without corrupting the original character array.我希望它在不破坏原始字符数组的情况下返回给定位置的标记。 The issue is that it return garbage on the first call, yet it works as expected on all subsequent calls.问题是它在第一次调用时返回垃圾,但它在所有后续调用中都按预期工作。 This should be a very simple fix, but I've been coding all day and I need a fresh set of eyes to back me up.这应该是一个非常简单的修复,但我已经编码了一整天,我需要一双新的眼睛来支持我。 (The hardcoded 350 is a given in this homework assignment, buffer shouldn't exceed 349 characters) (硬编码 350 是本作业中给定的,缓冲区不应超过 349 个字符)

You are returning pointer pointing non-static local variable, which will vanish on returning from the function and dereferencing the returned pointer from caller will invoke undefined behavior .您正在返回指向非静态局部变量的指针,该变量将在从函数返回时消失,并且从调用方取消引用返回的指针将调用未定义的行为

I guess you should copy the token before returning.我想你应该在返回之前复制令牌。 Add #include <stdlib.h> to use malloc() and free() .添加#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM