I've looked around but can't seem to find how to do this. I want the value of empty lines from test2(int *f) to be passed to test1() and be printed on the screen.
Variant 1 of code:
#include <stdio.h>
#include <string.h>
void test1();
void test2(int *f);
void test1(){
int a;
test2(&a);
printf("%d \n", a);
}
void test2(int *f){
char str[80];
int lines, i, emptylines=0;
*f=emptylines;
printf("Type a program here. Ctrl+Z and enter to stop.\n");
fflush(stdin);
while(gets(str)!=NULL && strcmp(str, "qq")) {
for(i=0; i<strlen(str); i++){
if(str[i]!='\n') lines=1;
}
if(!lines) emptylines++;
lines=0;
}
}
int main() {
test1();
return 0;
}
Variant 2 of code:
#include <stdio.h>
#include <string.h>
void test1();
void test2(int *f);
void test1(){
int a;
test2(&a);
printf("%d \n", a);
}
void test2(int *f){
char str[80], *p;
int lines, emptylines=0;
*f=emptylines;
printf("Type a program here. Ctrl+Z and enter to stop.\n");
fflush(stdin);
while(gets(str)!=NULL && strcmp(str, "qq")) {
p=str;
lines=0;
while(*p!='\0') {
if(*p!=' ') {
lines=1;
}
p++;
}
if(lines==0){
emptylines++;
lines=0;
}
}
}
int main() {
test1();
return 0;
}
You are putting *f=emptylines in the beginning of the function void test2(int *f); Then you calculate emptylines but this will not affect the value pointed-to by f.
You need to move that assignment *f=emptylines to the end of the function, just before returning and after having calculated emptylines
void test2(int *f){
// stuff to calculate emptylines
....
*f=emptylines; // at the end
}
When you write
*f = emptylines;
you are copying the value of emptylines into the space pointed to by f. Then when you update emptylines later, the value pointed to by f doesn't change because you made a copy.
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