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

时间:2017-12-13 17:59:54

标签: c string algorithm split

我有一个学校作业,我应该创建三个功能。函数是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

4 个答案:

答案 0 :(得分:1)

您的代码中存在很少的错误。更正将是

componentDidMount() {
    this.setState({
        thing: [
            {
                status: "running",
                test: "testing"
            }
        ]
    });
}

render() {
    return (
        <div>
            {this.state.thing.length > 0? <h1 className="mt-5 mb-5">{ this.state.thing[0].status }</h1>: null
}
            <button className="mt-5" onClick={ this.handleUpdate } value="not running">
                Click to change
            </button>
        </div>
    );
}

另一个是

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

最后一次

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

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

有些情况下,当你到达字符串的末尾但仍然没有获得空格。为避免这种情况,您还需要考虑if (words > wordCount) 案例。

如果\0那么只有你应该抛出错误。如果它们相等则应该打印该值。

答案 1 :(得分:1)

skipWords中的此循环是问题所在。它将遍历字符串并超越字符串,因为您没有检查字符串的结尾。

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

由于离开循环的唯一方法是找到与words传入的空格一样多的空格,因此它将始终返回NULL

可以说wordCount也应该从1开始,因为如果字符串中没有空格,除非字符串为空,否则你总是至少有一个单词。

答案 2 :(得分:1)

skipWords()中的算法已损坏,我将通过更改算法并将int更改为size_t来实现您的功能:

#include <stdio.h>
#include <stddef.h>
#include <ctype.h>

int printFirstWord(char const *inputString);
char const *skipWords(char const *sentence, size_t words);
int printWord(char const *sentence, size_t wordNumber);

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

int printFirstWord(char const *inputString) {
  int ret = 0;
  while (isblank(*inputString)) {
    inputString++;
  }
  while (!isblank(*inputString) && *inputString) {
    int tmp = printf("%c", *inputString++);
    if (tmp < 0) {
      return -1;
    }
    ret += tmp;
  }
  return ret;
}

char const *skipWords(char const *inputString, size_t words) {
  while (isblank(*inputString)) {
    inputString++;
  }
  while (words > 0) {
    words--;
    while (!isblank(*inputString)) {
      if (!*inputString) {
        return NULL;
      }
      inputString++;
    }
    while (isblank(*inputString)) {
      inputString++;
    }
  }
  return *inputString ? inputString : NULL;
}

int printWord(char const *sentence, size_t wordNumber) {
  char const *sentencePointer = skipWords(sentence, wordNumber);
  if (sentencePointer != NULL) {
    return printFirstWord(sentencePointer);
  } else {
    fprintf(stderr, "Error. Couldn't print the word.\n");
    return -1;
  }
}

答案 3 :(得分:1)

我们初学者应该互相帮助。:)

你在这里

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

char * skipWords( const char *s, size_t n )
{
    if ( n )
    {
        while ( isblank( ( unsigned char )*s ) ) ++s;

        do
        {
            while ( *s && !isblank( ( unsigned char )*s ) ) ++s;
            while ( isblank( ( unsigned char )*s ) ) ++s;
        } while ( *s && --n );
    }

    return ( char * ) ( *s ? s : NULL );
}

void printFirstWord( const char *s )
{
    while ( isblank( ( unsigned char )*s ) ) ++s;
    while ( *s && !isblank( ( unsigned char )*s ) ) putchar( *s++ );
}

void printWord( const char *s, size_t n )
{
    const char *word = skipWords( s, n );

    if ( word )
    {
        printFirstWord( word );
    }
    else
    {
        printf( "%s", "Error. Could not print the word." );
    }

    putchar( '\n' );
}

int main(void) 
{
    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); 

    return 0;
}

程序输出

I
like
to
eat
bunnies
Error. Could not print the word.
Error. Could not print the word.

至于你的代码,你通常不会检查终止零,例如

while (inputString[i] != ' ')
{
    printf("%c", inputString[i]);
    i++;
}

并忽略几个空格相互跟随的情况。