c - 数据结构 "stack"的结构变量的最终大小(通过结构实现并通过函数创建)

标签 c

所以我在大学学习数据结构stack,但是对它的实现和占用的内存有一些疑惑。

下面是我为它写的一小段代码:-

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

struct stack
{
    int *array;
    int top;
    int max_size;
};


struct stack createStack(int size)
{
    struct stack *Stack = malloc(sizeof(struct stack)); //line 1
    Stack -> max_size = size; //line 2
    Stack -> top = -1; //line 3
    Stack -> array = calloc(Stack -> max_size, sizeof(int)); //line 4
    return *Stack;
}

int main()
{
    int size; //Here lets say that size = 5
    scanf("%d", &size);

    printf("%ld", sizeof(createStack(size)));

    return 0;
}   

这里我通过 struct stack 定义了 Stack,如下面这部分代码所示:-

struct stack
{
    int *array;
    int top;
    int max_size;
};

现在上面的struct stack占用的内存应该是:-

8 bytes for int *array

4 bytes for int top

4 bytes for int max_size

因此占用/分配的总内存应该是16 字节

现在让我们来看有助于创建堆栈的代码的第二部分:-

struct stack createStack(int size)
{
    struct stack *Stack = malloc(sizeof(struct stack)); //line 1
    Stack -> max_size = size; //line 2
    Stack -> top = -1; //line 3
    Stack -> array = calloc(Stack -> max_size, sizeof(int)); //line 4
    return *Stack;
}

Here in line 1 we have allocated the sizeof struct stack(16 bytes) in structure variable *Stack. Hence size of * Stack is 16 bytes.

In line 2 and in line 3 values are initialised.

Now my question come from line 4

第 4 行中,我们将 20 个字节分配给 int *array(考虑到 max_size = 5)

现在 structure variable *Stack 的大小不应该是 28 字节 考虑到 int *array现在占用 20 字节 而不是 8 字节 ?

当我运行上面的代码时,它仍然提到sizeof 结构变量 *Stack is 16 bytes。我在这里缺少什么?

最佳答案

Now shouldn't the size of structure variable *Stack be 28 bytes considering that int *array now occupies 20 bytes instead of 8 bytes?

没有。 array 的大小仍然是 8 个字节。它仅包含大小为 20 字节的单独内存块的内存地址。该单独的 block 不是 *Stack 的一部分,不会影响其大小。

事实上,sizeof(createStack(size)) 不会调用您的函数,因此不会分配任何内存。 sizeof 只关心其操作数表达式的类型。由于 createStack 被声明为返回一个 struct stacksizeof createStack(...) 等同于 sizeof (struct stack)。所有这些都在编译时解决。

同样,如果你这样做

char arr[1000];
char *ptr = &arr[0];

那么 sizeof ptr 仍然是 8 因为 ptr 被声明为 char *sizeof (char *)是 8。这才是最重要的。


顺便说一下,如果你真的要调用 createStack,它会泄漏内存:

    struct stack *Stack = malloc(sizeof(struct stack));
    ...
    return *Stack;

第一行分配内存并将地址存储在Stack中。但是,这个地址并没有离开这个功能。仅返回结构本身的副本(通过 return *Stack)。该程序现在已经失去了对 malloc 返回的指针的跟踪,并且永远无法释放它。

修复:

    struct stack Stack;
    Stack.max_size = size;
    Stack.top = -1;
    Stack.array = calloc(Stack -> max_size, sizeof(int));
    return Stack;

关于c - 数据结构 "stack"的结构变量的最终大小(通过结构实现并通过函数创建),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743660/

相关文章:

c - AVR C : Serial Communication Clear Screen

c - 如何将数组作为地址发送到函数

c - C 中 strtol() 的奇怪崩溃

c - 使用多个提示和 scanf 运行 C 代码的更好方法

比较输入的字符串

c - 为什么 malloc() 可以互换调用 mmap() 和 brk()?

c - 调用 realloc() 之前释放内存

c - 将结构存储到文件并再次检索它

c - 程序替换字符串中的所有子字符串

python - 如何防止系统挂起/锁定(Python/C/Bash)