简体   繁体   English

将结构传递给 function 调用不起作用

[英]Passing struct to function call doesn't work

Since C does not support pass by reference, and I'm developing something that cannot use heap memory, how can I make this work?由于 C 不支持按引用传递,并且我正在开发一些不能使用堆 memory 的东西,我该如何使它工作? I want the function call set_var_name to actually change the variables global_log instead of just a local copy.我希望 function 调用 set_var_name 来实际更改变量 global_log 而不仅仅是本地副本。 Thanks谢谢

#include <stdio.h>
struct Record 
{ 
    char type[1];
    char var_name[1014];
    void* var_address;
    char is_out_dated[1];
}; 

struct Global_Log
{
    struct Record records[1024];
    int next_slot;
};

void set_var_name(struct Global_Log global_log, int next_slot, char* data, int size)
{
    for(int i = 0 ; i < size; i++)
        global_log.records[0].var_name[i] = data[i];
    printf("%s\n",global_log.records[0].var_name);//here prints out "hello"
}

int main()
{
    struct Global_Log global_log;
    char a[6] = "hello";
    set_var_name(global_log, 0, a, 6);
    printf("%s\n",global_log.records[0].var_name); // here prints out nothing
    return 0;
}

It seems that you are working with a copy of the struct instance, instead of a reference.您似乎正在使用 struct 实例的副本,而不是引用。 Try passing a pointer of a struct as a parameter, so you can work with a reference of the instance:尝试将结构的指针作为参数传递,这样您就可以使用实例的引用:

void set_var_name(struct Global_Log* global_log, int next_slot, char* data, int size)

Another alternative is using a global variable, since it sounds like there won't be another instance of it.另一种选择是使用全局变量,因为听起来好像不会有它的另一个实例。

C is a call-by-value language -- when you call a function, all arguments are passed by value (that is, a copy is made into the callee's scope) and not by reference. C 是一种按值调用的语言 - 当您调用 function 时,所有 arguments 都是按值传递的(即,副本是通过引用传递到被调用方的范围内)。 So any changes to the arguments in the function only affect the copy in the called function.因此,对 function 中的 arguments 的任何更改只会影响被调用的 function 中的副本。

If you want to call "by reference", you need to do it explicitly by passing a pointer and dereferencing it in the called function.如果你想调用“通过引用”,你需要通过传递一个指针并在被调用的 function 中取消引用来显式地完成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM