gpt4 book ai didi

c - 从函数返回 NULL 值到 C 中的指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:34 24 4
gpt4 key购买 nike

我有一个学校作业,我应该在其中创建三个函数。这些函数是 printFirstWord()、skipWords() 和 printWord()。

虽然写得不完美,但我设法使 printFirstWord 函数正常工作,而其他两个函数大部分工作正常。

但是,在 skipWords() 中,如果您希望跳过的单词数量大于您输入的字符串中的单词数量,我应该返回一个 NULL 指针值。这是我的代码:

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

//Call the functions
void printFirstWord(char inputString[]);
char* skipWords(char sentence[], int words);
void printWord(char sentence[], int wordNumber);

int main()
{
printWord("I like to eat bunnies", 0); //Prints I
printWord("I like to eat bunnies", 1); //Prints like
printWord("I like to eat bunnies", 2); //etc
printWord("I like to eat bunnies", 3);
printWord("I like to eat bunnies", 4);
printWord("I like to eat bunnies", 5); //This should return NULL
printWord("I like to eat bunnies", 6); //This should return NULL

return 0;
}

//Function that prints only the first word of a string
void printFirstWord(char inputString[])
{
int i = 0;

//Removes initial non-alpha characters, if any are present
while (!isalpha(inputString[i]))
i++;

//Checks if the next input is alphabetical or is the character '-'
while (inputString[i] != ' ')
{
printf("%c", inputString[i]);
i++;
}

}

char* skipWords(char sentence[], int words)
{
int i = 0, wordCount = 0;

for(i = 0; wordCount < words; i++)
{
if(sentence[i] == ' ')
{
wordCount++;
}
}

//Can't get this to work, not sure how to return NULL in a function
if (words >= wordCount)
return NULL;
else
return &sentence[i];
}

void printWord(char sentence[], int wordNumber)
{
char *sentencePointer;
sentencePointer = skipWords(sentence, wordNumber);

if (sentencePointer != NULL)
printFirstWord(sentencePointer);
else if (sentencePointer == NULL)
printf("\nError. Couldn't print the word.\n");
}

最初我的问题是程序经常崩溃,但我添加了 printWord 函数的最后一部分,它就停止了崩溃。我期待这样的输出:

Iliketoeatbunnies

Error. Couldn't print the word.

Error. Couldn't print the word.

这是我收到的输出:

Error. Couldn't print the word.

Error. Couldn't print the word.

Error. Couldn't print the word.

Error. Couldn't print the word.

Error. Couldn't print the word.

Error. Couldn't print the word.

指针是我的弱点,我觉得我错过了一些关键的东西,我一直在网上寻找,但我还没有找到适合我的解决方案,或者至少我觉得不适合我。

Assignment Description

最佳答案

您的代码中几乎没有错误。更正将是

for(i = 0; sentence[i] && wordCount < words; i++)

另一个是

while (inputString[i] !=' ' && inputString[i]!='\0')

最后一个

if (words > wordCount)

第一个的解释是——你不会检查超过字符串的末尾。否则你有未定义的行为。

可能会出现这样的情况,当您到达字符串的末尾但仍然找不到空格。为避免这种情况,您还需要考虑 \0 情况。

如果 words > wordCount 那么只有你应该抛出错误。如果它们相等,那么它应该打印值。

关于c - 从函数返回 NULL 值到 C 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47799489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com