3

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?

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.