請確保使用正確的類型。 (您應該很少使用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
使用'foo' – 2013-05-12 19:27:07
是什麼'g'請告訴我們的代碼?它應該不是'st'嗎? – karthikr 2013-05-12 19:27:21
在你的'foo'函數中,你傳遞'* st',但是使用'g-> a' ...這是故意的嗎? – Bill 2013-05-12 19:27:26