爲什麼我們在結構中聲明int *數組是什麼意思?
array
成員用於存儲堆棧的內容。但是,我們事先並不知道堆棧需要保存多少個元素,所以我們不能將其聲明爲常規數組(其大小必須在編譯時間處已知)。相反,我們將在運行時使用庫函數分配內存,該函數返回一個指向動態分配塊的第一個元素的指針;這個指針將被存儲到數組成員。
爲什麼我們寫結構堆疊*之前創建功能
因爲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
點的struct Stack
一個實例的stack
變量;這個實例是由該行創建的
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
在createStack
函數中。堆棧實例的內存取自「堆」(爲動態分配保留的內存區域)。內的棧實例中,array
構件也指向由另一個呼叫保留動態存儲器的區域以malloc
:
stack->array = (int*) malloc(stack->capacity * sizeof(int));
這個函數設置留出足夠的存儲器中作爲在capacity
構件指定用來存儲許多int
對象。
編輯
注意兩個malloc
呼叫可以被清理如下:
struct Stack *stack = malloc(sizeof *stack);
...
stack->array = malloc(stack->capacity * sizeof *stack->array);
除非您使用的是C++編譯器或C編譯器,早在1989年的標準,投是不必要的(並且在C89實現上,很危險)。
sizeof
表達式使用解除引用的目標表達式,而不是類型名稱;這將清理一些視覺混亂,並且如果您決定更改目標變量的類型(例如,從int *
到double *
),它會減少維護。表達式*stack
的類型是struct Stack
,所以它遵循sizeof *stack == sizeof (struct Stack)
。類似地,表達*stack->array
的類型是int
,因此sizeof *stack->array == sizeof (int)
。請注意,只有在sizeof
的操作數是類型名稱時才需要括號。
1. C99引入可變長度數組,其大小可以在運行時被指定,但在這方面有以下幾個原因它們將不起作用。
不要被冒犯,但你需要有'c'數據類型的基礎課程。有很多基本的概念問題。 –
'int *'不是一個數組,它是一個指針。 –
Unsigned表示無符號整數。 – andyn