我试图了解堆栈结构的工作原理,但由于某种原因,每当我尝试从中打印时charElements
,我的程序崩溃了,我不知道为什么。这是我不断收到的错误:(它在断点处)while (i-- && *p)
。但我不知道我如何宣布一切有什么问题。有什么想法吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct Stack
{
int capacity; // max # of elements the stack can hold
int size; // current size of the stack
int *elements; // the array of elements
char *charElements; // the array of chars
}Stack;
Stack * createStack(int maxElements)
{
// Create a Stack
Stack *S;
S = (Stack *)malloc(sizeof(Stack));
// Initialise its properties
S->charElements = (char *)malloc(sizeof(int)*maxElements);
S->elements = (int *)malloc(sizeof(int)*maxElements);
S->size = 0;
S->capacity = maxElements;
/* Return the pointer */
return S;
}
int main()
{
Stack *S = createStack(60);
char registerNames[63] = {"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
// if the user input a a string
S->elements[S->size++] = 1;
S->elements[S->size++] = 2;
S->elements[S->size++] = 3;
S->charElements[S->size++] = *registerNames;
printf("%d \n", S->elements[0]);
printf("%d \n", S->elements[1]);
printf("%d \n", S->elements[2]);
printf("%d \n", S->size);
printf("%s \n", S->charElements[3]);
system("pause");
return 0;
}