简体   繁体   中英

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? I want the function call set_var_name to actually change the variables global_log instead of just a local copy. 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. 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. So any changes to the arguments in the function only affect the copy in the called 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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