你好,我有一个非常基本的问题,对初学者来说非常困惑
让我说有一个像这样的代码
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做的是a = a + b;两者都在结构上。
我也希望使用指针* st作为函数foo的参数。
我一次又一次地解除引用错误。我的代码有什么问题?我该怎么办?
答案 0 :(得分: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;
}
答案 1 :(得分: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