【发布时间】: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_)来增加取消引用值。其他变量也一样