c - k&r 练习 1.8 结构成员

标签 c

所以我只是在完成 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/

相关文章:

C 字符串解析和转换

c - 如何添加两个字符串

c - 如何在 C 中为 __func__ 赋值?

c - 在 C 中,main() 方法最初是如何调用的?

c - 这个 k&r 第 2 章的例子错了吗?

c - 将 char 数组中的指针分配给字符串 C 中的每个单词

c++ - 使用按位运算符和 bool 逻辑的绝对值 abs(x)

c - 了解这种情况下的预处理器指令吗?

c - 为什么字符串数组中的 "Hello"的大小为 4?

c - 循环数组会导致我的程序崩溃