user11739097
user11739097

Reputation:

Passing to pointer to char in function and read value in caller

I want to pass pointer to a function which pass this pointer to another function which points to the array and after this function end I want read the value in the caller function.

So this is the example code how I want it to work:

void fun_1(const char *data)
{
  /* some code */
  fun_2(data);
}

void fun_2(const char *data)
{
  /* some code */
  fun_3(data);
}

static bool fun_3(const char *data)
{
  static char buffer[20];
  /* some code */
  data = buffer;
  return true;
}

And to function fun_1 I want pass static char *resp and after fun_3 end I want to have address of buffer and then read out from it but now when fun_3 ends the resp is always NULL.

Upvotes: 0

Views: 85

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

C is pass by value. Assigning to a local variable inside a function is transient, the effect will not pass to the caller’s parameter variable.

In your case I suspect you don’t want to use assignment but rather strcpy or memcpy to copy the buffer into a buffer provided by the calling code.

Be careful that the calling code allocates a sufficiently large buffer though, and make the caller pass in the buffer size to avoid overriding the available space:

static bool fun_3(const char *data, size_t size) {
  char buffer[20];
  if (size < sizeof buffer) return false;

  /* some code */
  memcpy(data, buffer, sizeof buffer);
  return true;
}
char buffer[25];
bool success = fun_3(buffer, sizeof buffer);

Alternatively, if you really want to return a pointer to a local static variable (but think carefully about the implications! In particular thread safety), you can either

  • return the pointer:

    char *fun_3() {
      static char buffer[20];
      /* some code */
      return buffer;
    }
    
    char *buffer = fun_3();
    
  • pass by pointer:

    static bool fun_3(const char **data) {
      static char buffer[20];
      /* some code */
      *data = buffer;
      return true;
    }
    
    char* buffer;
    bool result = fun_3(&buffer);
    

Upvotes: 2

Related Questions