所以我只是在完成 k&r 的基本练习。 练习是: 练习 1-8。编写一个程序来计算空格、制表符和换行符。
我尝试创建一个包含成员空白、制表符 和换行符 的结构。 我还编写了一个 init 函数来将这些成员设置为 0。
我现在将向您展示源代码和输出。
/*
Exercise 1-8. Write a program to count blanks, tabs, and newlines.
*/
#include <stdio.h>
typedef struct Counter Counter;
struct Counter
{
int blanks;
int tabs;
int newlines;
};
void initCounter(Counter arg)
{
arg.blanks = 0;
arg.tabs = 0;
arg.newlines = 0;
};
int main()
{
int c;
Counter cnt;
initCounter(cnt);
while((c = getchar()) != EOF)
{
if(c == ' ')
{
++cnt.blanks;
}
if(c == '\t')
{
++cnt.tabs;
}
if(c == '\n')
{
++cnt.newlines;
}
}
printf("\nBlanks: %d", cnt.blanks);
printf("\nTabs: %d", cnt.tabs);
printf("\nNewlines: %d\n", cnt.newlines);
return 0;
}
这是输出:
give it another try boom
Blanks: -416565517
Tabs: 32768
Newlines: 1
有什么问题的建议吗? 谢谢并致以最诚挚的问候。
最佳答案
void initCounter(Counter arg)
{
arg.blanks = 0;
arg.tabs = 0;
arg.newlines = 0;
};
您需要传递一个指向arg
的指针。您正在初始化传递给 initCounter
的结构对象的副本。在 C 函数中,参数按值传递。
你的函数原型(prototype)应该是:
void initCounter(Counter *arg)
{
/* ... */
}
我让您对 initCounter
主体和 initCounter
函数调用进行适当的更改。
关于c - k&r 练习 1.8 结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21741470/