C - 结构段错误

标签 c struct segmentation-fault stack

如果这是一个容易解决的问题,我真的很抱歉,但我是初学者。 我有一项任务是将一些函数写入堆栈结构。给出了结构。我无法摆脱 push() 行“s->elements...”中的段错误 经过几个小时的谷歌搜索和搜索后,我不知道出了什么问题。

这里是代码:

#define STACK_SIZE 5<p></p>

#include <stdio.h>
#include <stdlib.h>

typedef struct stackADT {
    int elements[STACK_SIZE];
    int count;
} stack;

void initialize(stack *s)
{
     stack *newStack;
     newStack = malloc(sizeof(*newStack));
     newStack->count = 0;

     s = newStack;
}

int push(stack *s, int value)
{
    if(s->count == 5) return -1;
    else {
        s->elements[s->count++] = value;
        return s->elements[s->count-1];
    }
}

int main()
{
    stack* sA;
    stack* sB;
    initialize(sA);
    initialize(sB);
    printf("%d\n",push(sA,3));
    return 0;
}

最佳答案

我认为你需要像下面这样的东西

#include <stdio.h>

#define STACK_SIZE  5

typedef struct stackADT 
{
    int elements[STACK_SIZE];
    int count;
} stack;

void initialize( stack *s )
{
    s->count = 0;
}

int push( stack *s, int value )
{
    return s->count == STACK_SIZE ? -1 : ( s->elements[s->count++] = value );
}

int main(void) 
{
    stack sA;
    stack sB;

    initialize( &sA );
    initialize( &sB );

    printf( "%d\n", push( &sA, 3 ) );

    return 0;
}

关于C - 结构段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375859/

相关文章:

在 C 中复制一个带有字符串成员的结构

c - C中的'do'关键字

C 段错误 - 链表

c - 如何在 C 中返回多维数组元素的索引?

c++ - 我可以在 Vista 和 Windows 7 下以用户模式获得对原始磁盘扇区的写访问权限吗?

c - 为什么给数组结构赋值不起作用 C

C 将结构传递给函数

java - 有没有办法将结构字段作为数组访问?

c - 将c字符串解析为指针数组时出现段错误

c++ - 任何想法如何使 C++ 在内核错误上抛出异常