2013-10-08 44 views
-2

我有一個分配結構傳遞的指向函數的指針我的代碼的麻煩(簡言之)是結構體和用C

struct userCom{ 
    int x; 
    int y; 
} 

main(void){ 
    struct userCom com; 
    userComFunction(com); 
    printf("%d", com.x); 
} 

userComFunction(struct userCom *return_type){ 
    struct userCom temp; 
    temp.x = 10; 
    printf("%d", temp.x); 
    *return_type = temp; 
} 

功能這將打印

10 
11537460 

上午我路過通過指針錯誤? 我似乎無法弄清楚爲什麼com.x不等於10

+1

您需要將引用傳遞給指針。嘗試'userComFunction(&com)' –

+1

嘗試編譯時啓用所有警告(例如gcc -Wall)。這應該指出問題。 – Chris

+1

btw你缺少返回類型的函數。使用'gcc -Wall'選項。 –

回答

3

正如其他人指出的那樣,問題是您將錯誤類型的參數傳遞給userComFunction。但真正的問題是你的編譯器沒有告訴你。從C90開始(這是兩個標準之前的版本),調用沒有可見聲明的函數是合法的,編譯器會對函數的實際外觀做出假設(通常是不正確的)。當編譯器看到對userComFunction的調用時,它沒有看到userComFunction的聲明或定義,因此它無法診斷您的錯誤。

從C99開始,調用沒有可見聲明的函數是違反約束的,這意味着編譯器至少必須警告您。 C99也刪除了「隱含的int」規則,因此您不能再在函數聲明中省略返回類型; main應聲明爲int返回類型(而不是void!)和userComFunction,因爲它不返回任何內容,應該是void

您可以移動的userComFunction完整定義的main上面的定義,或者你可以離開定義它在哪裏,並添加一個「前進」的聲明:

void userComFunction(struct userCom *return_type); 

int main(void) { 
    /* ... */ 
} 

void userComFunction(struct userCom *return_type) { 
    /* ... */ 
} 

當你這樣做時,編譯器應該讓你知道你的電話:

userComFunction(com); 

不正確。 (修復方法是將com更改爲&com。)

您還應該使用gcc的命令行選項啓用更多警告。例如:

gcc -std=c99 -pedantic -Wall -Wextra 

-std=c99表示強制執行ISO C99規則。 -pedantic說要確實強制執行這些規則。 -Wall-Wextra啓用其他警告。

+0

我總是懷疑你的答案。你不會錯過任何你應該成爲老師:) –

+0

還應該使用'-pedantic-error'來進行更多的檢查? –

+1

@GrijeshChauhan:('-pedantic-errors'將'-pedantic'啓用的警告轉化爲致命錯誤。)這取決於。如果你有將所有警告視爲需要解決的問題的政策,那麼'âpedantic'和''pedantic-errors''之間沒有太大的實際區別。如果您確實需要在某些情況下編寫不可移植的代碼,並且您確實知道自己在做什麼,那麼'-pedantic'可以警告您潛在的問題,並且您可以自行決定是否相應地更改代碼。對於嘗試編寫可移植代碼的初學程序員來說,'-pedantic-errors'可能是一個好主意。 –

0

如果你想把10賦給x,那麼你應該這樣做。 以下是正確的代碼:

struct userCom{ 
int x; 
int y; 
} 
void struct userComFunction(struct userCom*); 
main(void) 
{ 
struct userCom com; 
userComFunction(&com); 
printf("%d\n", com.x); 
} 

userComFunction(struct userCom *return_type){ 
struct userCom temp; 
temp.x = 10; 
printf("%d\n", temp.x); 
return_type->x= temp.x; 
}