使用指针来计算 _ 和 !在 C 的 main 函数之外的字符串中

Using pointers to count _ and ! in a string outside of the main function in C

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

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);

}

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

您有 Undefined behavior in your code. *++p_num_; increments the pointer first and then it dereferences it. The value of it is not used. And this way, the pointer points to some memory which are not the variables you supposed it to be. Then you dereference it - that location contains indeterminate value and you print it. Accessing some memory which you don't have permisssion to is - UB.

(*p_num_)++ 

是你想要的那个。这也适用于另一个变量——即 p_num_exclamation。另外 getchar 的 return 值是 int 而不是 char - 你应该使用 int 来保存由 getchar 编辑的值 return .