[英]Struct Segmentation fault: 11. Unable to reassign values in a struct first initialized to null
I am very new to using a struct
so some of the code I am about to show may just be incorrect and that may be the cause of the error I am getting. 我对使用
struct
非常struct
因此我要显示的某些代码可能只是不正确,而这可能是导致我得到错误的原因。 I am writing code trying to imitate stacks using a struct
. 我正在编写代码,尝试使用
struct
模仿堆栈。 I am currently trying to make a pushInt()
function that takes in a pointer to a stack struct
and some int
value. 我目前正在尝试制作一个
pushInt()
函数,该函数接受指向堆栈struct
的指针和一些int
值。 This is the code that I have for the puchInt()
function: 这是我为
puchInt()
函数编写的代码:
Stack *pushInt(Stack *stack, int value)
{
stack->intTop = TRUE;
stack->data.intValue = value;
stack->next = NULL;
return stack;
} // end pushInt
This is the code that I use to define the stact struct
. 这是我用来定义stact
struct
的代码。 It is a self referencing struct to act like a likedList: 这是一个自引用结构,其行为类似于LikedList:
struct StackNode
{
int intTop;
union {
int intValue;
char stringValue[MAX_STRING_LENGTH];
} data;
struct StackNode *next;
};
This is the main function that I run to test the functionality of the code: 这是我运行以测试代码功能的主要功能:
int main()
{
Stack *theStack = NULL;
//getInteger function just gets user input
int pushValue = getInteger("value to push onto stack: ");
theStack = pushInt(theStack, pushValue);
}
theStack = pushInt(theStack, pushValue); theStack = pushInt(theStack,pushValue);
Here the NULL Pointer (theStack initialised with NULL) is passed. 这里传递了NULL指针(用NULL初始化的theStack)。 So it becomes De-referencing the NULL pointer inside pushInt function and hence the seg fault.
因此,它成为取消引用pushInt函数中的NULL指针,从而导致seg错误。
You need to allocate memory to the variable theStack 您需要为变量theStack分配内存
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.