在C中,不能从函数返回数组。这是基于设计决策的语言在其开发过程中的一个特点。你有几个选择,这可能不是一个全面的清单:
动态分配内存,并返回指向该静态地声明函数中的数组,返回指向它的指针(因为它是静态的,它将继续存在于函数的生命周期之外)将数组包装在结构中,返回结构创建一个所有函数都能看到的全局数组,不要担心返回任何东西。我个人的偏好是选项1,如下所示
代码语言:javascript复制char** split_message(const char* message, size_t* numWords)
{
// You could do a single scan through message and reallocate space
// as needed, but in order to avoid that complexity, I'm going to do
// 2 scans through message. The first will discover where all the spaces
// are, and naively assume 1) only one space separates words and 2) there
// is a word on either size of a space. The second scan will actually
// tokenize message based on the space separators
// initialize numWords
*numWords = 0;
// get the length of message once
size_t messageLen = strlen(message);
// first scan, loop until we hit the NUL terminator at the end of message
for (size_t i=0; i<=messageLen; i++)
{
if (message[i] == ' ' || message[i] == '\0')
{
// increase word count when we see a space or get to the NUL
// terminator
(*numWords)++;
}
}
printf("numWords = %zu\n", *numWords);
// Now we know how many words we have, allocate space for them
char** retWords = malloc(*numWords * sizeof(*retWords));
if (retWords == NULL) exit(-1); // handle out of mem error how you want
// second scan
size_t wordStartIndex = 0;
size_t wordIndex = 0;
for (size_t i=0; i<=messageLen; i++)
{
if (message[i] == ' ' || message[i] == '\0')
{
// save the word length to a local
size_t wordLength = i - wordStartIndex;
// found the next space
// allocate space, +1 for NUL terminator
retWords[wordIndex] = malloc(wordLength + 1);
if (retWords[wordIndex] == NULL) exit(-1); // handle error
// copy the word into the buffer
memcpy(retWords[wordIndex], message + wordStartIndex, wordLength);
// NUL terminate
retWords[wordIndex][wordLength] = '\0';
// update indexes
wordIndex++;
// _assumes_ next word starts after this space. That could be a
// bad assumption depending on message
wordStartIndex = i+1;
}
}
return retWords;
}请注意,我是如何做到的,这并不是防弹的。领导,尾随,和多个空格之间的文字会抛出东西,可能会造成问题,我还没有广泛地测试它。它也不排除任何可能存在的标点符号。
工作演示
我也认为你这样做是为了锻炼。如果没有,则使用strtok代替。
问560宝骏自动挡怎么样
微信亲密付怎么开通,微信亲密付开通步骤详解