简体   繁体   中英

pointer to struct member

typedef struct
{   
    int A;
    int B;

    char* C; // problem is here
}foo;

int SetA(void)
{
    ....
    return retval;
}

int SetB(void)
{
    ....
    return retval;
}

const char* bar(void)
{
    .....
    char* retval="return val";
    .....
    return retval;
}

void SetFoo(foo* paramFoo)
{
paramFoo->A = SetA();
paramFoo->B = SetB();

paramFoo->C = bar();

}


static foo staticFoo;

void main()
{   
    SetFoo(&staticFoo);
    printf("%s",staticFoo.C);// printing
}

everything will go fine but the "char*C" in struct foo will not be written well. why? i need to know if i did mistake and how too correct it?. i've ran the bar() and it returns the correct value.

Thank you ~ Max

I would prefer using malloc and later free it, so that I dont have to worry about when the read only string literal get destroyed.

 const char* bar(void) 
 {     
     const char* retval="return val";
     char * value = malloc( strlen(retval) + 1 ); // +1 for the termination 
                                                  // character
     strcpy( value, retval );
     retrun value ;
 }

Remember to free the return value when no longer needed.

Something appears to be wrong with the example as you've stated it, because it should actually work.

A couple of the other answers given seem to focus inaccurately on the idea that bar is returning a local variable, but it isn't -- the string it returns is allocated at compile time and is not dynamically allocated on the stack. A pointer to said string is, in fact, technically safe to return to later code.

My guess is that your example isn't an accurate reflection of your actual test code.

the string in function bar is a local variable. you need to create it by malloc a memory buffer or declare it a global variable.

 char* bar(void) 
 {     
     char* retval=malloc(100*sizeof(char)); //malloc the buffer
     strcpy( retval,"return val");
     retrun retval ;
 }

or

char * str = "return val";
const char* bar(void)
{
    .....
    char* retval = str;
    .....
    return retval;
}

I agree with the Perry's answer. A constant string is allocated in read only data section, not on the stack. In foo() you are returning a constant string, it can be safely accessed from any where.

First of all you have typed the code manually. You did not compile it. In your main you have code like this:

   SetFoo(&staticfoo);
   printf("%s",staticFoo.C);

You see that both the objects staticfoo and staticFoo are not same. If you fix it and run the program you should get the string printed. It printed in my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM