C 引用指针作为函数的参数并更改其引用值
你好,我有一个问题,这是非常基本的和相当混乱的初学者 让我说有这样的代码C 引用指针作为函数的参数并更改其引用值,c,C,你好,我有一个问题,这是非常基本的和相当混乱的初学者 让我说有这样的代码 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的参数 我一次又一次地犯了解引用错误。我的代码有什么问题?我该怎么办呢?
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的参数
我一次又一次地犯了解引用错误。我的代码有什么问题?我该怎么办呢?这样就可以了
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;
}
确保使用正确的类型。(您应该很少使用
void*
)使用&
运算符获取地址(创建指向的指针)
请使用
foo
什么是g
?如果它不是st
?在foo
函数中,您传递*st
,但使用g->a
…这是故意的吗?也不是st
是void
指针,g
指向您的结构,哦,我很抱歉使用了g。这是圣。我马上就去试试。您能给我一些提示或快捷方式来了解*和&?声明(返回类型、函数参数、变量声明…)中的*
表示“指针”structure*st
表示st
是一个指针,包含structure
类型的内存位置。语句中使用的引用运算符&
通常被称为“address of”-运算符。foo(&gee)将gee的地址传递到foo()中,foo()将是指针st
@user2375570的值,不客气。欢迎来到StackOverflow!记住对任何有帮助的答案进行投票,并“接受”最能回答您问题的答案。@YHG这就是它的工作原理,只能有一个被接受的答案。
#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;
}