Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 引用指针作为函数的参数并更改其引用值_C - Fatal编程技术网

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;
}