1

Possible Duplicate:
Trouble with returning a string from function
Can a local variable’s memory be accessed outside its scope?

I'm trying to use a function to modify the value of a String pointer. I declared a struct called someStruct, and one of the fields is a pointer to a string, named 'valu'. Here's what I did:

void func(char* nvalue,someStruct* container){
    char temp[strlen(nvalue+1);
    temp=strcpy(temp,nvalue);
    container->valu=temp;
    return;

Will this function modify the value of the container to be nvalue? If not, how can I do it? I'm really not good with C so any help would be nice! Thank you

Community
  • 1
  • 1
turtlesoup
  • 3,188
  • 10
  • 36
  • 50
  • `temp=strcpy(temp,nvalue);` isn't legal and you're missing a `]` on the line above for starters. – Flexo Jan 27 '13 at 11:36
  • `container->valu=temp;` This is wrong as `temp` is a local array and you are assigning it to a pointer and expect it to be valid outside the function. This is undefined behaviour in C. – P.P Jan 27 '13 at 11:39

1 Answers1

1

Since tmp is a local variable, accessing to container->value outside of the function is an undefined behavior. However, it is possible to use dynamic allocation to control the lifetime of your variable.

#include <stdlib.h>
#include <string.h>

char **p = &container->value;

*p = malloc(strlen(nvalue) + 1);

if (*p != NULL)
{
  strcpy(*p, nvalue);
}
md5
  • 23,373
  • 3
  • 44
  • 93
  • What does it mean to control the lifetime of the variable? If I use malloc I have to free the memory somewhere else right? Is that what you meant? Or does it get automatically freed? – turtlesoup Jan 27 '13 at 11:48
  • @user1926344: No, `container->value` won't be automatically freed. Its lifetime will be extended until a `free` call, whereas `temp` in your example has a limited lifetime (block). – md5 Jan 27 '13 at 12:04