2013-05-12 47 views
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做mak​​e a = a + b;这两者都在结构中。

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

和我一次又一次解除引用错误。我的代码有什么问题?我该怎么做?

+0

使用'foo' – 2013-05-12 19:27:07

+0

是什么'g'请告诉我们的代码?它应该不是'st'吗? – karthikr 2013-05-12 19:27:21

+0

在你的'foo'函数中,你传递'* st',但是使用'g-> a' ...这是故意的吗? – Bill 2013-05-12 19:27:26

回答

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 
+0

哦,我明白了.. iguess ..非常感谢你。谢谢 – YHG 2013-05-12 19:37:11

+0

@ user2375570不客气。欢迎来到StackOverflow!请记住对任何有帮助的答案进行投票,并“接受”最能回答您问题的答案。 – 2013-05-12 19:42:27

+0

为什么不能同时接受?两者都极其有帮助 – YHG 2013-05-12 19:45:06

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

我会立即尝试。你能否给我一些提示或快捷方式来了解*和&的区别? – YHG 2013-05-12 19:32:35

+0

声明中的'*'(返回类型,函数参数,变量声明...)表示“指针”。 'struct * st'意味着'st'是一个指针并且包含一个类型为'structure'的内存位置。语句中使用的引用操作符“&”通常被称为“操作符地址”操作符。 foo(&gee)将gee的地址传递给foo(),而foo()又是指针“st”的值。 – Pixelchemist 2013-05-12 19:36:02

+0

也谢谢你的课程 – YHG 2013-05-12 19:37:44