确保使用正确的类型。(您应该很少使用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