0

你好,我有一个非常基本的问题,对于初学者来说很困惑

让我说有这样的代码

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 做的是 make a = a+b; 两者都在结构上。

而且我想使用指针 *st 作为函数 foo 的参数。

我一次又一次地得到解除引用错误。我的代码有什么问题?我该怎么办?

4

2 回答 2

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;
}
于 2013-05-12T19:28:50.423 回答
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
于 2013-05-12T19:29:10.480 回答