pavikirthi
pavikirthi

Reputation: 1655

pass by reference a struct through multiple functions in C

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;
}

Upvotes: 0

Views: 712

Answers (1)

harmands
harmands

Reputation: 1112

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;
}

Upvotes: 1

Related Questions