0

I tried to google my problem many times but never found an answer that fits my problem. I have to modify a pointer to a structure inside a function(fill it with data), and then use that pointer as an argument to another functions. I have a text file that has multiple reports in it and I am supposed to count the reports and fill all the data to a pointer to a structure. Which isnt a problem, I allocated memory without a problem, got through the file without a problem and also filled the pointer. But I can't figure out how to use the filled pointer outside of the function.

struct report{
  char name[50];
  int id_number;
}

void function1(struct report **ptr){
  //do stuff like count the number of reports in file
  //and allocate memmory for pointer to structure
  //and fill the pointer to structure with data
}
int main() {
  struct report *pointer;
  function(pointer);
  //now I expect variable 'pointer' to be filled and ready to use by another functions
  return 0;
}

Can you please suggest some solutions please? Thank you for your time and help.

1
  • Do you allocate the memory in function1 on the heap? Commented Oct 29, 2018 at 9:33

1 Answer 1

2

Please have a look at the example:

#include <stdlib.h>
#include <stdio.h>

struct report{
  char name[50];
  int id_number;
};

void foo(struct report **ptr){
  *ptr = malloc(sizeof(struct report));  // allocate memory
  (*ptr)->id_number = 42;  // fill the allocated memory
}

int main() {
  struct report *pointer;
  foo(&pointer);  // important part - pass to the foo() pointer to the pointer.

  printf("%d\n", pointer->id_number);

  free(pointer);  // do not forget to free the memory.
  return 0;
}
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.