2013-05-12 49 views
0

你好,我有一個問題,這是很基本的,對於初學者相當混亂引用指針的函數參數和改變其參考價值

讓我說有這樣

typedef struct st { 
int a; 
int b; 
} structure 

structure gee; 
gee.a =3; 
gee.b =5; 

void foo(void (*st)){ 
g->a += g->b; 
} 

一個代碼,所以我想用函數foo做mak​​e a = a + b;這兩者都在結構中。

而且我想使用指針* st作爲函數foo的參數。

和我一次又一次解除引用錯誤。我的代碼有什麼問題?我該怎麼做?

+0

使用'foo' – 2013-05-12 19:27:07

+0

是什麼'g'請告訴我們的代碼?它應該不是'st'嗎? – karthikr 2013-05-12 19:27:21

+0

在你的'foo'函數中,你傳遞'* st',但是使用'g-> a' ...這是故意的嗎? – Bill 2013-05-12 19:27:26

回答

0

請確保使用正確的類型。 (您應該很少使用void*。)使用&運算符來獲取地址(創建指針)。

#include <stdio.h> 

typedef struct st { 
int a; 
int b; 
} structure;     // <--- You were missing a semicolon; 

structure g_gee = { 3, 5 }; // This guy is global 
// You can't do this, you have to use a struct initializer. 
//gee.a =3;      
//gee.b =5; 

void add_a_b(structure* g) { 
    g->a += g->b; 
} 

void print_structure(const char* msg, structure* s) { 
    printf("%s: a=%d b=%d\n", msg, s->a, s->b); 
} 

int main(int argc, char** argv) { 
    structure local_s = { 4, 2 };  // This guy is local to main() 

    // Operate on local 
    print_structure("local_s before", &local_s); 
    add_a_b(&local_s); 
    print_structure("local_s after", &local_s); 

    // Operate on global 
    print_structure("g_gee before", &g_gee); 
    add_a_b(&g_gee);   
    print_structure("g_gee after", &g_gee); 

    getchar(); 
    return 0; 
} 

輸出

local_s before: a=4 b=2 
local_s after: a=6 b=2 
g_gee before: a=3 b=5 
g_gee after: a=8 b=5 
+0

哦,我明白了.. iguess ..非常感謝你。謝謝 – YHG 2013-05-12 19:37:11

+0

@ user2375570不客氣。歡迎來到StackOverflow!請記住對任何有幫助的答案進行投票,並「接受」最能回答您問題的答案。 – 2013-05-12 19:42:27

+0

爲什麼不能同時接受?兩者都極其有幫助 – YHG 2013-05-12 19:45:06

0

這將做到這一點。

typedef struct { 
int a; 
int b; 
} structure; 

void foo(structure * st){ 
st->a += st->b; 
} 

int main (void) 
{ 
    structure gee; 
    gee.a =3; 
    gee.b =5; 
    foo(&gee); 
    return 0; 
} 
+0

我會立即嘗試。你能否給我一些提示或快捷方式來了解*和&的區別? – YHG 2013-05-12 19:32:35

+0

聲明中的'*'(返回類型,函數參數,變量聲明...)表示「指針」。 'struct * st'意味着'st'是一個指針並且包含一個類型爲'structure'的內存位置。語句中使用的引用操作符「&」通常被稱爲「操作符地址」操作符。 foo(&gee)將gee的地址傳遞給foo(),而foo()又是指針「st」的值。 – Pixelchemist 2013-05-12 19:36:02

+0

也謝謝你的課程 – YHG 2013-05-12 19:37:44