2012-03-22 52 views
-1
int assign(int *m){ 
    //static int n = 9; 
    // m = &n; // will assign the value to the variable a = 9 
    *m = 10; 
    // int n =8; 
    // m = &n; // will fail as the scope of the variable is within the function 
    return 0; 
} 

int main(){ 
    int a ; 
    assign(&a); 
    printf("%d",a); 
    return 0; 
} 

ANS:A = 10是否有任何其他的方式來獲得在輸出(而不經過地址和使用該指針和參數的函數)從另一個功能獲得的輸出值在C

+4

你可以做'int assign(){return 10;}'和主'a = assign();'將值賦給a。 – twain249 2012-03-22 13:27:46

+0

誰是「他」?他爲什麼輸出價值? – Wes 2012-03-22 13:28:20

+0

是的,如果你不需要返回值用於其他目的,那麼...使用它是什麼:返回值! :)否則不,你在C中沒有任何其他選項(你可能會考慮返回一個結構而不是原始類型,但對於性能來說這是一個壞主意)。 – 2012-03-22 13:30:30

回答

2

C中的每個函數都允許您返回單個值。

int assign(......) 
^ 
| 
output type 

您可以使用return關鍵字。返回某個東西的函數就像其他任何具有相同類型的表達式一樣。

例如,如果您有:

int assign(void) 
{ 
    return 10; 
} 

下面所有的都是有效的:

int a = assign(); 
int b = (assign()*20)-assign()/assign(); 

爲什麼你可能需要在辯論中使用指針的原因是爲了多單輸出。

例如,採取越過一個數組,並返回最小值和最大值的功能:

void minmax(int *array, int size, int *minimum, int *maximum) 
{ 
    int i; 
    int min_overall = INT_MAX; 
    int max_overall = INT_MIN; 
    /* error checking of course, to make sure parameters are not NULL */ 
    /* Fairly standard for: */ 
    for (i = 0; i < size; ++i) 
    { 
     if (array[i] < min_overall) 
      min_overall = array[i]; 
     if (array[i] > max_overall) 
      max_overall = array[i]; 
    } 
    /* Notice that you change where the pointers point to */ 
    /* not the pointers themselves: */ 
    *minimum = min_overall; 
    *maximum = max_overall; 
} 

,並在您main,你可以使用它像這樣:

int arr[100]; 
int mini, maxi; 
/* initialize array */ 
minmax(arr, 100, &mini, &maxi); 

編輯:既然您問是否有其他方式來做到這一點,下面是一個例子(儘管我絕對不推薦它像你這樣的用法):

struct assign_ret 
{ 
    int return_value; 
    int assigned_value; 
}; 

struct assign_ret assign(void) 
{ 
    assign_ret ret; 
    ret.assigned_value = 10; 
    ret.return_value = 0; 
    return ret; 
} 

main

struct assign_ret result = assign(); 
if (result.return_value != 0) 
    handle_error(); 
a = result.assigned_value; 

爲什麼我不建議這樣做的原因,是struct是用來放置那些相關的數據一起。功能錯誤返回值與其數據輸出無關。