Setting two pointers equal in a helper function

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

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

      

I have another function where I declare that disk_ptr will point to the disk address (but not allocate any memory). I want to pass disk_ptr to a helper function that will call the disk constructor and set disk_ptr to the same address as the pointer that 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 is currently pointing nowhere, and does the following:

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:

Drive Pointer: 0x6000509f0 Drive Pointer: 0xb

Although I can access the disk structure variables from "create_or_update_disk_from_file" - I cannot access the disk structure variables from the process_current_directory calling it.

What would be the correct way for disk_ptr to point to the same address as the output of the disk_constructor?

+3


source to share


1 answer


Pass disk_ptr as a structured disk ** so you can change 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);

      

+4


source







All Articles