为什么我得到一个返回值3221225477



我正在尝试在C中实现堆栈。我没有得到任何编译错误,但我得到了322122547的返回值,没有任何错误。我该怎么办?

这是我的代码

#include <stdio.h>
#include <stdlib.h>
struct stack
{
int size;
int top;
int *arr;
};
int isEmpty(struct stack * ptr)
{
if (ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct stack * ptr)
{
if (ptr->top == ptr->size - 1)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
struct stack *s;
s->size = 10;
s->top = -1;
s->arr = (int *)malloc(s->size * sizeof(int));
if(isEmpty(s)){
printf("The stack is empty");
}
else{
printf("The stack is not empty");
}
return 0;
}

如果我使用结构堆栈指针,我不会得到任何输出。我应该考虑更改指针部分吗

打开编译器错误,它会立即告诉你哪里出了问题。例如,如果我用gcc -Wall -Werror编译你的代码,它会说:

error: 's' is used uninitialized [-Werror=uninitialized]
s->size = 10;
| ~~~~~~~~^~~~

问题来源

struct stack *s;正在定义一个指针,该指针期望您的结构的实例。现在默认情况下,预期的结构没有初始化,因此指针指向内存中的一个随机位置。

您可以通过使用gcc -Wall -Werror编译来可视化此错误,并获得:

error: 's' is used uninitialized [-Werror=uninitialized]
s->size = 10;
| ~~~~~~~~^~~~

由于指针指向的位置是随机的,您将根据该内存位置包含的内容从指针中获得随机值。

解决方案

解决此问题的方法是初始化指针期望指向的结构,以便分配此结构。你可以通过两种方式做到这一点:

  • 静态分配:您可以创建一个结构,然后使用以下方法指向它:
struct stack s_static;
struct stack *s = &s_static;

最后的代码是:

int main()
{
struct stack s_static;
struct stack *s = &s_static;
s->size = 10;
s->top = -1;
s->arr = (int *)malloc(s->size * sizeof(int));
if(isEmpty(s)){
printf("The stack is empty");
}
else{
printf("The stack is not empty");
}
return 0;
}
  • 动态分配:您可以使用malloc在内存中动态分配结构。您可以通过执行struct stack* s = (struct stack*) malloc(sizeof(struct stack));来分配您的堆栈实例s。这是一条很大的线。发生了什么事?struct stack* s告诉编译器这是一个指向内存位置的指针。(struct stack*)告诉malloc,我们将要分配的新内存位置的类型为struct stack。最后,malloc在堆上为我们的实例创建一些空间,sizeof(struct stack)简单地"告诉"malloc命令我们需要分配多少内存。在放入这一行之后,代码将在没有错误的情况下编译。

    但是等一下!如果使用动态分配,还需要在完成后释放堆,否则内存位置将泄漏。因此,在return 0之前,您需要释放该内存位置。您可以使用free(s)最终的动态分配方法看起来是这样的:
int main()
{
struct stack* s = (struct stack*) malloc(sizeof(struct stack));    
s->size = 10;
s->top = -1;
s->arr = (int *)malloc(s->size * sizeof(int));
if(isEmpty(s)){
printf("The stack is empty");
}
else{
printf("The stack is not empty");
}
free(s);
return 0;
}

最新更新