为什么我们在结构体中声明int*数组是什么意思?
array 成员用于存储堆栈的内容。但是,我们无法提前知道堆栈需要容纳多少元素,因此我们不能将其声明为常规数组(其大小必须在编译时知道1)。相反,我们将在运行时使用malloc 库函数分配内存,该函数返回指向动态分配块的第一个元素的指针;这个指针将被存储到数组成员中。
为什么我们要在创建函数之前写 struct Stack *
因为createStack 函数返回一个指向新struct Stack 实例的指针:
struct Stack *createStack( ... ) ----------------+
{ | The type of the expression in the
struct Stack *stack = ...; -----+ | `return` statement must match the
... | | return type of the function
return stack; <-----------------+---------------+
}
这里的无符号有什么用
unsigned 是unsigned int 的缩写;它保证只有非负值可以用于堆栈大小。
这是调用createStack 函数后的内存样子:
+---+
stack: | |----+ // The stack variable points to a struct Stack instance
+---+ |
... |
+---+ |
stack->top: | |<---+ // The actual struct Stack instance is created on the heap
+---+ // The -> operator allows us to refer to the members of the
stack->capacity: | | // instance through the stack pointer variable.
+---+
stack->array: | |----+ // The memory for the stack contents is allocated in a
+---+ | // separate malloc call, and the resulting pointer is
... | // stored in the instance's array member.
+---+ |
stack->array[0]: | |<---+
+---+
stack->array[1]: | |
+---+
stack->array[2]: | |
+---+
...
+---+
stack->array[N-1]: | | // N == stack->capacity
+---+
main 中的stack 变量指向struct Stack 的一个实例;这个实例是由行创建的
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
在createStack 函数中。堆栈实例的内存取自“堆”(为动态分配保留的内存区域)。在堆栈实例中,array 成员还指向另一个调用 malloc 保留的动态内存区域:
stack->array = (int*) malloc(stack->capacity * sizeof(int));
此函数留出足够的内存来存储int 成员中指定的int 对象。
编辑
请注意,两个malloc 调用都可以按如下方式清理:
struct Stack *stack = malloc( sizeof *stack );
...
stack->array = malloc( stack->capacity * sizeof *stack->array );
除非您使用的是 C++ 编译器或早于 1989 年标准的 C 编译器,否则强制转换是不必要的(并且在 C89 实现上是危险的)。
sizeof 表达式使用取消引用的目标表达式,而不是类型名称;这会清理一些视觉上的混乱,如果您决定更改目标变量的类型(例如,从int * 到double *),它会减少维护。表达式*stack 的类型是struct Stack,所以它遵循sizeof *stack == sizeof (struct Stack)。同样,表达式*stack->array 的类型是int,所以sizeof *stack->array == sizeof (int)。请注意,仅当 sizeof 的操作数是类型名称时才需要括号。
1。 C99 引入了
可变长度数组,其大小
可以在运行时指定,但由于多种原因,它们在这种情况下不起作用。