char 数组正在破坏我的堆栈结构。我声明有什么错误吗?

标签 c crash stack arrays

我试图获得关于堆栈结构如何工作的直觉,但由于某种原因,每当我尝试从 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/

相关文章:

objective-c - 我的应用程序崩溃并关闭,关于原因的信息很少

c++ - 使用 Stack 实现 C++

c - aarch64 中的结构对齐

c - C 代码中带有 union 的意外输出

iphone - UILocalNotification 在我启动它时使我的应用程序崩溃

java - Tigase xmpp 服务器在使用 Tsung 进行测试时崩溃

C程序退出时没有任何提示

c - 无法从 C 中的 HTTP 请求获取路径和方法

c++ - 使用堆栈检查正确的HTML标记的C++程序

assembly - 清理堆栈时可以将动态值(寄存器或内存)与 RET 一起使用吗?