简体   繁体   English

如何重新分配结构指针

[英]How to reassign a struct pointer

I am trying to reassign a Person pointer in a function called 'nameChanger', what am I doing wrong? 我正在尝试在名为“ nameChanger”的函数中重新分配Person指针,我在做什么错呢? how can I reassign a Person pointer, to point to another Person ? 如何重新分配一个Person指针以指向另一个Person

#include <stdio.h>  
#include <string.h> 

typedef struct {
    int age;
    char name[50];
} Person;

void nameChanger(Person ** person);

int main() {
    Person brian;
    brian.age = 27;
    strcpy(brian.name, "brian");

    Person * brian_pointer = &brian;

    nameChanger(&brian_pointer);
    printf("changing name to 'rick' :  %s\n", brian_pointer->name); // should be 'rick'

    return 0;
}

void nameChanger(Person ** person){
    Person rick;
    rick.age = 50;
    strcpy(rick.name, "rick");

    Person * rick_p = &rick;
    *person = &rick;
}

The problem here, is rick is local to the nameChanger function. 这里的问题是rick对于nameChanger函数是本地的。 Once the function finshes execution, rick will cease to exist. 一旦函数完成执行, rick将不再存在。 So, the returned pointer and any reference will be invalid. 因此,返回的指针和任何引用将无效。

You can make rick a pointer, and allocate memory using malloc() and family. 您可以使rick成为指针,并使用malloc()和family分配内存。 In that way, the lifetime of the allocated memory will be until the memory is free() -d, so after returning, the access will be valid. 这样,分配的内存的生存期将一直到该内存为free() d为止,因此在返回之后,访问将是有效的。

You need to be aware that your local variable rick is allocated on the stack frame of function nameChanger() , when the function returns, the memory is not valid any more, you should not use that address outside the function. 您需要注意,您的局部变量rick是分配在函数nameChanger()的堆栈框架上的,当函数返回时,内存不再有效,您不应在函数外部使用该地址。

If you need to do that, use malloc() instead, or declare the variable as global variable outside of any function. 如果需要这样做,请改用malloc() ,或在任何函数外部将变量声明为全局变量。

Try understand memory layout of a process, especial about stack & function in your case. 尝试了解进程的内存布局,尤其是您所用的堆栈和功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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