2016-09-18 34 views
-2

我試圖發送一個結構數組作爲參考,但由於某種原因,我不能得到它的工作,因爲價值是能夠通過,但並不作爲參考(&)通行證結構陣列的功能使用指針

這是我的代碼:

#include <stdio.h> 
#include <string.h> 

struct mystruct { 
    char line[10]; 
}; 

void func(struct mystruct record[]) 
{ 
    printf ("YES, there is a record like %s\n", record[0].line); 
} 

int main() 
{ 
    struct mystruct record[1]; 
    strcpy(record[0].line,"TEST0"); 
    func(record);  
    return 0; 
} 

我以爲只有通過調用函數func(&記錄),並改變FUNC功能參數爲「結構MYSTRUCT *記錄[]」這是去上班......但是它沒有。

請任何幫助。

+0

「不工作」,是不是你遇到什麼問題的一個非常有用的描述。請告訴我們你得到的輸出。 – kaylum

+0

當我嘗試引用這個錯誤時有點奇怪,但這是它: – Marco

+2

C沒有引用傳遞,所有東西都是按值傳遞的。但'func(record)'已經傳遞了'record'數組作爲指針。也就是說,它已經通過「引用」,就像你想要的一樣(它不會複製整個結構數組)。 – kaylum

回答

-2

我認爲你已經把你的指針和引用概念混淆了。

func(&record)會傳遞變量記錄的地址而不是引用。

傳遞指針

#include <stdio.h> 
#include <string.h> 

struct mystruct { 
    char line[10]; 
}; 

void func(struct mystruct * record) 
{ 
    printf ("YES, there is a record like %s\n", record[0].line); 
    // OR 
    printf ("YES, there is a record like %s\n", record->line); 
} 

int main() 
{ 
    struct mystruct record[1]; 
    strcpy(record[0].line,"TEST0"); 
    func(record); // or func(&record[0]) 
    return 0; 
} 

,如果你必須通過一個參考,試試這個

#include <stdio.h> 
#include <string.h> 

struct mystruct { 
    char line[10]; 
}; 

void func(struct mystruct & record) 
{ 
    printf ("YES, there is a record like %s\n", record.line); 
} 

int main() 
{ 
    struct mystruct record[1]; 
    strcpy(record[0].line,"TEST0"); 
    func(record[0]); 
    return 0; 
} 

更新

爲了解決這個評論(縣)以下,

  • 引用在純C中不可用,僅在C++
  • 原代碼「斷層」是一個struct mystruct record[]應該已經struct mystruct & record
+0

哦,是的,這正是我正在尋找的,指針的第一個選項,我混淆了關於引用的東西,因爲這些指針可以幫助您模擬相同的事物。謝謝 – Marco

+3

這個問題被標記爲'c',所以沒有任何引用。你只能在'C++'中獲得引用。 –

+2

C不支持引用。而且你沒有指出問題代碼中的錯誤。 – Olaf