所以我在大学学习数据结构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
forint *array
4 bytes
forint top
4 bytes
forint 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 sizeofstruct stack
(16 bytes
) in structure variable*Stack
. Hence size of* Stack
is16 bytes
.In
line 2
and inline 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 thatint *array
now occupies 20 bytes instead of 8 bytes?
没有。 array
的大小仍然是 8 个字节。它仅包含大小为 20 字节的单独内存块的内存地址。该单独的 block 不是 *Stack
的一部分,不会影响其大小。
事实上,sizeof(createStack(size))
不会调用您的函数,因此不会分配任何内存。 sizeof
只关心其操作数表达式的类型。由于 createStack
被声明为返回一个 struct stack
,sizeof 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/