Pointers and local variables

时间:2017-06-20 12:34:36

标签: c pointers memory-management scope

I was given this code in an exam, and needed to explain what it does: (I changed some names, since the source was not English)

#include <stdlib.h>

typedef int typeInfoSCL;
struct elemSCL
{
    typeInfoSCL info;
    struct elemSCL* next;
};

typedef struct elemSCL TypeElemSCL;
typedef TypeElemSCL* TypeSCL;

void list_add(TypeSCL *scl, typeInfoSCL e)
{
    TypeSCL tmp = *scl;
    *scl = malloc(sizeof(struct elemSCL));
    (*scl)->info = e;
    (*scl)->next = tmp;
}

int main()
{
    TypeSCL scl1 = NULL;
    list_add(&scl1, 3);
    list_add(&scl1, 5);
    TypeSCL tmp = malloc(sizeof(struct elemSCL));
    tmp->next = scl1;
    list_add(&tmp, 7);
}

I thought that since tmp is a local variable in list_add, this statement:

(*scl)->next = tmp;

would be incorrect, since after the method is invoked, scl->next no longer exists.

Tests proved me wrong. Why is that so?

1 个答案:

答案 0 :(得分:2)

While the variable tmp is a local variable, with the assignment

(*scl)->next = tmp;

you don't make (*scl)->next point to the variable, instead you just copy the contents of tmp (which is the location of where it is pointing) into (*scl)->next.

After the assignment you have two pointers ((*scl)->next and tmp) both pointing to the same memory. When the function returns and tmp goes out of scope (*scl)->next will still keep its value and continue to point to the same memory.