Home > Software design >  Why can't I access my pointer of char through my function?
Why can't I access my pointer of char through my function?

Time:11-13

#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

CodePudding user response:

 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

  • Related