简体   繁体   English

在堆栈上分配的作用域结构

[英]Scope struct allocated on the stack

I am reading and learning on C. I have read many similar questions but most of them seem to be a counter example of what I am experiencing or I still don't understand the concept of object allocation on the heap and on the stack. 我正在阅读和学习C语言。我已经阅读了许多类似的问题,但是大多数问题似乎只是我所遇到的问题的反例,或者我仍然不了解堆和栈上对象分配的概念。

Suppose I have a struct like in the following example: 假设我具有以下示例中的结构:

typedef struct {
    int x;
    char* word;
    struct list_element* next;
}list_element;

I want to write a function that initialises a struct of the type list_element . 我想编写一个函数来初始化类型为list_elementstruct What I would do from what I learned from text books is create the struct on the heap using malloc so everything is still visible outside the initialiser function. 从我从教科书中学到的东西,我会做的是使用malloc在堆上创建结构,因此在初始化函数之外,所有内容仍然可见。

list_element* init_list_element(int x, char* word) {

    list_element* le = (list_element*)malloc(sizeof(list_element));
    le->word = word;
    le->x = x;

    return le;
}

For truly understanding the subject I tried to write an alternative initialiser function that allocates the struct on the stack. 为了真正理解该主题,我尝试编写一个替代的初始化函数,该struct在堆栈上分配该struct Which should result in an error later when trying to access the attributes because the variable should have gone out of scope. 稍后尝试访问属性时,这将导致错误,因为变量应该超出范围。

list_element init_list_element(int x, char* word) {
    list_element le;
    le.word = word;
    le.x = x;

    return le;
}

However when creating a struct with the second implementation and trying to access for example the attribute x the code doesn't break. 但是,当使用第二种实现创建结构并尝试访问例如属性x时,代码不会中断。 Why is this? 为什么是这样? Shouldn't the variable le be gone out of scope and therefor inaccessible when trying to printf its attributes? 尝试打印其属性时,变量le是否不应该超出范围并因此无法访问?

list_element test = init_list_element(123,"test");
printf("%s, %i", test.word, test.x);
list_element test = init_list_element(123,"test");

You are creating a copy of the struct created inside the second function, therefore you can still access it, but it's just a copy. 您正在创建在第二个函数内部创建的结构的副本,因此您仍然可以访问它,但这只是一个副本。

In C, everything you assign to variable is a copy. 在C语言中,您分配给变量的所有内容都是副本。

Example: 例:

list_element le1 = {1, NULL, NULL};
list_element le2 = le1;

le2 will contain a copy of le1 and not the original le1. le2将包含le1的副本,而不是原始的le1。 In other words, the following will not change the value of le1: 换句话说,以下内容不会更改le1的值:

le2.x = 3;
printf("%d",le1.x); // 1
printf("%d",le2.x); // 3

The variable le has gone out of scope, but you are not accessing le . 变量le超出范围,但是您没有访问le The init_list_element() function returns a copy of le , and the contents of that copy are assigned to test . init_list_element()函数返回le的副本,并将该副本的内容分配给test

The members of test then contain the same data that le originally did. 然后, test成员包含与le最初相同的数据。

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

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