Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

k&r exercise 1.8 structure members

Tags:

c

so I am just going through the basic exercises of the k&r. The exercise is: Exercise 1-8. Write a program to count blanks, tabs, and newlines.

I tried to create a structure with the members blanks,tabs and newlines. I also coded an init function to set these members to 0.

I will now show you the source code and the output.

/*
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;
}

This is the output:

give it another try boom

Blanks: -416565517
Tabs: 32768
Newlines: 1

Any advice what's going wrong? Thanks and best regards.

like image 637
pfjupfju Avatar asked Feb 13 '23 19:02

pfjupfju


1 Answers

void initCounter(Counter arg)
{
    arg.blanks = 0;
    arg.tabs = 0;
    arg.newlines = 0;   
};

You need to pass a pointer to arg. You are initializing a copy of the structure object you pass to initCounter. In C function arguments are passed by value.

Your function prototype should be:

void initCounter(Counter *arg)
{
    /* ... */
}

I let you make the appropriate changes to initCounter body and initCounter function call.

like image 92
ouah Avatar answered Feb 28 '23 13:02

ouah