【问题标题】:Using pointers to count _ and ! in a string outside of the main function in C使用指针计数 _ 和 !在 C 中 main 函数之外的字符串中
【发布时间】:2018-02-25 17:46:38
【问题描述】:

我正在为学校做作业,但无法获得正确的输出。我不确定我的循环是否存在问题,或者使用指针保存值的方法是否存在问题。当我运行代码时,我最终会得到这样的结果:

Output: There are 369224989 underscores and 0 exclamation points in the sentence. 

赋值指定使用原型和 getchar() 函数来读取输入。我觉得由于第一个值是如此之高,这是我的循环的一个问题,但我已经为此工作了两天并且没有发现任何问题(尽管此时我可能正在盯着它)。 此外,当我尝试编译程序时会收到这些警告:

characters.c:28: warning: value computed is not used
characters.c:31: warning: value computed is not used

这让我觉得它可能与主函数没有正确通信。

#include<stdio.h>
 //this function prototype was required for the assignment

void count(int* num_, int* num_exclamation);

// intended to count the number of _ and ! in a string using pointers

int main()
{
        int num_, num_exclamation;

        count(&num_, &num_exclamation);

        return 0;
}


void count(int* p_num_, int* p_num_exclamation)
{
        char ch;

        *p_num_ = *p_num_exclamation = 0;

        //attempts to scan a string get the first character
        printf("Enter a sentence: ");
        ch = getchar();

        //attempts to loop while incrementing if it is a ! or _

        while(ch != '\n')
                {
                if(ch == '_')
                        *++p_num_;

                if(ch == '!')
                        *++p_num_exclamation;

                ch = getchar();

                }
        //prints result

        printf("Output: There are %d underscores and %d exclamation points 
in the sentence.\n", *p_num_, *p_num_exclamation);

}

这是我第二次真正与指针进行交互,第一次是这个任务的另一半,它工作正常。我对它们不是特别满意,也不知道它们的所有细微差别。任何能让我找到正确位置的建议都将不胜感激。

【问题讨论】:

  • 您的代码中有未定义的行为。
  • *++p_num_; 递增指针,然后取消引用它。您应该使用++(*p_num_) 来增加取消引用值。其他变量也一样

标签: c pointers getchar


【解决方案1】:

您的代码中有Undefined behavior*++p_num_; 首先增加指针,然后取消引用它。它的值没有被使用。这样,指针指向的内存不是您认为的变量。然后你取消引用它 - 该位置包含不确定的值并打印它。访问一些您无权访问的内存是 - UB

(*p_num_)++ 

是你想要的。这也适用于另一个变量 - 即p_num_exclamation。同样getchar 的返回值是int 而不是char - 你应该使用int 来保存getchar 返回的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多