ADL92
ADL92

Reputation: 11

Why can't I access my pointer of char through my function?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h> 
#include <unistd.h>
#include <ctype.h>
#include <assert.h>


void *process(char **nbE) 
{
   char buffer[8] = "test";

   *nbE = &buffer[0];
   printf("%s\n", *nbE);
}

int main(int argc, char **argv) 
{
   char *str;
   process(&str);

   printf("%s\n", str);
}

I'm trying to get the value of *nbE in main() by making it points to the address of first char in my array. But it returns something not encoded, why?

What would be a way for me to do this way?

Note: I know I can do it simpler, I have a more complex code and this is a mini example

Basically I have something interesting in my array and want to pass it to my main function through a char* variable

Upvotes: 0

Views: 51

Answers (1)

pm100
pm100

Reputation: 50110

 char buffer[8] = "test";

creates a string that is local to the function, it is destroyed once you return from that function. Do this

 static char buffer[8] = "test";

or

  char * buffer = strdup("test");

you have to release the string when you have finsihed with it in the second case

Upvotes: 1

Related Questions