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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With