2016-12-29 76 views
3

我環顧四周,但似乎無法找到如何做到這一點。我希望將test2(int *f)的空行值傳遞給test1()並打印在屏幕上。代碼從一個void函數到另一個使用指針的值?

變1:代碼

#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; 
} 

變2:

#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; 
} 
+0

你已經顯示了一些代碼,但沒有描述你與他們有什麼問題。你也沒有問過有關該代碼的問題。所以目前還不清楚你要求什麼幫助。 – kaylum

+0

'fflush(stdin)'調用未定義的行爲。 IOW:你的代碼被設計破壞了。 'gets'不再是標準的一部分,**永遠不會**使用它! – Olaf

+0

這不是第一個問題的一部分,也不是第一個問題的一部分,而是用whan代替get? SCANF? – MESA

回答

4

你把*f=emptylines在功能void test2(int *f);然後你計算emptylines的開始,但是這不會影響價值指向f

您需要在分配*f=emptylines移動到函數的結尾,就返回之前和已經計算emptylines

void test2(int *f){ 
    // stuff to calculate emptylines 
    .... 

    *f=emptylines; // at the end 
} 
3

當你寫

*f = emptylines; 

要複製的價值進入f指向的空間。然後,當您稍後更新emptylines時,f所指向的值不會因爲您創建副本而更改。

1

而不是使用其他變量emptylines只是直接使用參數f來計算值。雖然我會給它比f更具描述性的價值,比如numEmptyLines

#include <stdio.h> 
#include <string.h> 
void test1(); 
void test2(int *numEmptyLines); 
void test1(){ 
    int a; 
    test2(&a); 
    printf("%d \n", a); 
} 
void test2(int *numEmptyLines){ 
    char str[80]; 
    int lines, i; 
    *numEmptyLines = 0; 
    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) (*numEmptyLines)++; 
       lines=0; 
    } 
} 
int main() { 
    test1(); 
    return 0; 
} 
相關問題