0

I am trying to pass a struct by reference through multiple functions but I am getting garbage value when I try to print the value of the struct in each function. How to correctly pass it by reference, so that the value is passed back until from func3() -> func2() -> func1()-> main() function

typedef struct _buf {
   void  *ptr;
   size_t len;
} buf;


int func3(buf *x){
  x->ptr = 45;
  printf("func3 %s \n", (char *)x->ptr);
  return 0;
}

int func2(buf *x){
  func3(&* x);
  printf("func2 %s \n", (char *)x->ptr);
  return 0;
}


int func1(buf *x) {
  func2(&*x);
  printf("func1 %s \n", (char *)x->ptr);
  return 0;
}


int main() {
  buf x = {NULL, 0};
  func1(&x);
  printf("main %s \n", (char *)x.ptr);
  return 0;
}
4
  • 1
    you are trying to print the string at address 45 - what do you expect the output to be? Commented Apr 3, 2018 at 18:48
  • 4
    Your functions are already receiving a pointer. just pass the pointer. to the next function. For example func2(&*x); -> func2(x); Commented Apr 3, 2018 at 18:48
  • What happens if you don't pass the pointer along but put the code inline? If you did that, you'd see that the argument passing isn't the problem. Also, it's irrelevant that it's a pointer to a struct. It's for that reason that you are required to provide a minimal reproducible example! Commented Apr 3, 2018 at 18:50
  • When you dereference x-ptr in func3 you are asking to see what is at memory location 45, which almost certainly will cause an exception/ Commented Apr 3, 2018 at 18:52

1 Answer 1

1

Without many changes to your code, I have fixed two things here.

1) You are trying to print a string starting from the address 45. That is an issue, obviously it will print garbage.

2) You can pass the pointer forward as it is.

#include<stdio.h>
typedef struct _buf {
   void  *ptr;
   size_t len;
} buf;


int func3(buf *x){
  x->ptr = (void*)"hello";
  printf("func3 %s \n", (char *)x->ptr);
  return 0;
}

int func2(buf *x){
  func3(x);
  printf("func2 %s \n", (char *)x->ptr);
  return 0;
}


int func1(buf *x) {
  func2(x);
  printf("func1 %s \n", (char *)x->ptr);
  return 0;
}


int main() {
  buf x = {NULL, 0};
  func1(&x);
  printf("main %s \n",(char*) x.ptr);
  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.