Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting two pointers equal in a helper function

I have create a structure called "Disk". I also created a constructor for the disk which returns a pointer to the disk structure.

struct disk {...}
struct disk* construct_disk(char*, char*, char*, char*, int, char*, int*);

I have another function within which I declare that disk_ptr will point to an address of the disk (but do not allocate any memory). I want to pass disk_ptr into a helper function which will call the disk constructor and set disk_ptr to point to the same address as the pointer which the disk constructor returns.

int process_current_directory(health_monitor* hm, char* directory){
    ...
    struct disk* disk_ptr;
    //PROBLEM IS HERE - disk_ptr is not assigned value correctly below
    create_or_update_disk_from_file(current_directory, disk_ptr, CREATE);
    printf("The disk pointer is: %p\n", disk_ptr");
    ...
}

So, create_or_update_disk_from_file takes this pointer which currently points nowhere, and does this:

void create_or_update_disk_from_file(char* filename, struct disk* disk_ptr, int action){
    ...
    // This is where I want to disk_ptr to be assigned
    disk_ptr = construct_disk(name, serial, vendor, model, rpm, raid_type, input); 
    printf("The disk pointer is: %p\n", disk_ptr");
    ...
}

The two print statements give me the following values for pointers:

The disk pointer is: 0x6000509f0 The disk pointer is: 0xb

And while I can access structure variables of the disk from within "create_or_update_disk_from_file" - I cannot access the disk structure variables from the function that calls it, process_current_directory.

What would be the right way to have disk_ptr point to the same address as the output of construct_disk?

like image 777
RebeccaK375 Avatar asked Dec 30 '25 22:12

RebeccaK375


1 Answers

Pass disk_ptr as a struct disk ** so you can modify it.

void create_or_update_disk_from_file(char* filename, struct disk** disk_ptr, int action){
    ...
    *disk_ptr = construct_disk(name, serial, vendor, model, rpm, raid_type, input); 
    printf("The disk pointer is: %p\n", *disk_ptr");
    ...
}

and call it like this-

create_or_update_disk_from_file(current_directory, &disk_ptr, CREATE);
like image 60
Brad Avatar answered Jan 01 '26 12:01

Brad