我试图获得关于堆栈结构如何工作的直觉,但由于某种原因,每当我尝试从 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;
}
最佳答案
printf("%s \n", S->charElements[3]);
S->charElements[3]
是 char
,而不是 char *
。因此,当您尝试将其打印出来时,您将取消引用错误的内存地址并崩溃。
使用 printf("%c\n",S->charElements[3]);
打印出该位置的 char
。
另外,请注意
S->charElements[S->size++] = *registerNames;
将仅从 registerNames
复制一个字符,因为它将其视为 char
取消引用。如果您想复制字符串,请使用 strcpy
(但要确保有足够的空间!!)
关于char 数组正在破坏我的堆栈结构。我声明有什么错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13061572/