2012-01-08 222 views
1

我遇到了一個例子,它由Kernighan & Ritchie以「C語言編程」返回一個結構體。返回指向結構體的指針

/* binsearch: find word in tab[0]...tab[n-1] */ 
struct key *binsearch(char *word, struct key *tab, int n) 
{ 
    int cond; 
    struct key *low = &tab[0]; 
    struct key *high = &tab[n]; 
    struct key *mid; 

    while (low < high) { 
     mid = low + (high-low)/2; 
     if ((cond = strcmp(word, mid->word)) < 0) 
      high = mid; 
     else if (cond > 0) 
      low = mid + 1; 
     else 
      return mid; 
    } 

    return NULL; 
} 

看來,該函數正在返回一個指向函數中的本地變量的指針;這不是一個返回懸掛指針的情況嗎?

回答

7

不,這個函數不會返回一個指向局部變量的指針。事實上,在這個函數中根本沒有局部變量struct key

該函數返回一個指針,指向由其調用者提供給該函數的tab數組中的struct key元素之一。

1

不是在這種情況下,因爲只有指針是本地的,而不是結構本身,因爲它們從外部傳遞到參數tab

1

我想你是指在page #137中提到的binsearch代碼。爲了更好地理解代碼,您需要閱讀page #138中給出的解釋。

@K&R

@The C Programming Language

@Second Edition