【发布时间】: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 = &sData; ... return sDataPtr;不允许返回局部变量的地址。 -
sDataPtr = &sData;您返回一个指向局部变量的指针,一旦strSplit完成,该变量将不复存在。不要返回指针到splitResultStruct简单地返回一个splitResultStruct。 -
“结构中所有剩余的变量都可以。”该结构的所有其他字段也无效,因为您返回的指针指向的整个结构不再有效。它的生命已经结束
标签: c