【问题标题】:Passing back C struct with a char pointer array included fails传回包含 char 指针数组的 C 结构失败
【发布时间】:2022-11-10 18:41:16
【问题描述】:

我正在努力使用基于 C 的拆分函数。在从 strSplit() 函数通过引用返回结构后,令牌句柄似乎是错误的。变量 sd->tokens 是正确的地址,但我无法获取令牌。但它们是正确的,因为在函数内部我可以得到它。 我该如何解决这个问题以及这种行为的原因是什么。结构中所有剩余的变量都可以。

#include <stdio.h>
#include <string.h>

struct splitResult {
    char *source;
    long lSource;
    int  result;
    char **tokens;
};

typedef struct splitResult splitResultStruct;

splitResultStruct * strSplit(char *source, char *delimiter);

int main(int argc, const char * argv[]) {

    char *source = "part1.part2.part3";
    splitResultStruct *sd;
    
    sd = strSplit(source, ".");
    
    printf("%d tokens found\n", sd->result);
    
    for(int i=0; i<sd->result; i++) {
        printf("%s\n", sd->tokens[i]);
    }

    return 0;
}


splitResultStruct * strSplit(char *source, char *delimiter) {
    
    // Defines the result struct
    splitResultStruct sData, *sDataPtr;
    
    sDataPtr = &sData;
    
    sData.source = source;
    // Gets the length of source string
    sData.lSource = strlen(source);
    // Don't split if empty string is given
    if(sData.lSource == 0) {
        sData.result = -1;
        return sDataPtr;
    }
    // Allocate memory according teh size of source string
    char data[sData.lSource];
    // Copy the source into the allocated memory
    strcpy(data,source);
    // Just count the tokens
    char *token = strtok(data, delimiter);
    int tc = 0;
    while (token != NULL)
    {
        token = strtok(NULL, delimiter);
        tc++;
    }
    if(tc == 0) {
        sData.result = -1;
        return sDataPtr;
    }
    // Defines an array of char pointer with the dimension of the number of tokens
    sData.result = tc;
    char *tokens[tc];
    // Resets the token engine
    strcpy(data,source);
    // Strip out the first token found
    token = strtok(data, delimiter);
    tokens[0] = token;
    tc = 0;
    while (token != NULL)
    {
        // Strip out one token and store them into the token array
        token = strtok(NULL, delimiter);
        tc++;
        tokens[tc] = token;
    }
      
    sData.tokens = tokens;

    for(int i=0; i<sData.result; i++) {
        printf("%s\n", sData.tokens[i]);
    }

    return sDataPtr;
}

【问题讨论】:

  • sDataPtr = &amp;sData; ... return sDataPtr; 不允许返回局部变量的地址。
  • sDataPtr = &amp;sData; 您返回一个指向局部变量的指针,一旦 strSplit 完成,该变量将不复存在。不要返回指针到splitResultStruct 简单地返回一个splitResultStruct。
  • 这回答了你的问题了吗? error: function returns address of local variable
  • “结构中所有剩余的变量都可以。”该结构的所有其他字段也无效,因为您返回的指针指向的整个结构不再有效。它的生命已经结束

标签: c


【解决方案1】:

请记住,永远不要返回指向局部变量的指针。 局部变量在函数返回时被销毁。

尝试:

sDataPtr = malloc(sizeof(splitResultStruct));

或者:

static splitResultStruct sData;
splitResultStruct* sDataPtr;

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 2011-03-19
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多