A
arnuld
OBJECTIVE: To implement a stack (LIFO) using C array
WHAT I GOT: Segfault
I know there is something wrong with Line 73, where I add an element to
the array but what exactly is wrong I am not sure (except that a pointer
to pointer is being passed in function argument):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { VAL_FALSE = 0, VAL_TRUE = 1, SIZE_STACK = 10 };
struct myStruct
{
char* title;
};
struct myStack
{
int top;
};
void initialize(struct myStack s);
int stackEmpty(struct myStack s);
void push(struct myStruct* arr[], struct myStack s, const char* ele);
int main(void)
{
struct myStruct* sof[SIZE_STACK+1] = {0};
struct myStack s;
initialize(s);
stackEmpty(s);
push(sof, s, "CLC");
return 0;
}
int stackEmpty(struct myStack s)
{
if(s.top) return VAL_FALSE;
return VAL_TRUE;
}
void initialize(struct myStack s)
{
s.top = 0;
}
void push(struct myStruct* arr[], struct myStack s, const char* ele)
{
if(NULL == arr || NULL == ele)
{
fprintf(stderr, "IN: %s @%d: Invalid Args\n", __FILE__, __LINE__);
}
else if(SIZE_STACK <= s.top)
{
printf("Stack Full, Can not add anymore elements\n");
}
else
{
struct myStruct* p = malloc( 1 * sizeof *p);
if(NULL == p)
{
fprintf(stderr, "IN: %s @%d: Out of Memory\n", __FILE__,
__LINE__);
}
else
{
strcpy(p->title, ele);
arr[s.top] = p;
s.top += 1;
}
}
}
WHAT I GOT: Segfault
I know there is something wrong with Line 73, where I add an element to
the array but what exactly is wrong I am not sure (except that a pointer
to pointer is being passed in function argument):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { VAL_FALSE = 0, VAL_TRUE = 1, SIZE_STACK = 10 };
struct myStruct
{
char* title;
};
struct myStack
{
int top;
};
void initialize(struct myStack s);
int stackEmpty(struct myStack s);
void push(struct myStruct* arr[], struct myStack s, const char* ele);
int main(void)
{
struct myStruct* sof[SIZE_STACK+1] = {0};
struct myStack s;
initialize(s);
stackEmpty(s);
push(sof, s, "CLC");
return 0;
}
int stackEmpty(struct myStack s)
{
if(s.top) return VAL_FALSE;
return VAL_TRUE;
}
void initialize(struct myStack s)
{
s.top = 0;
}
void push(struct myStruct* arr[], struct myStack s, const char* ele)
{
if(NULL == arr || NULL == ele)
{
fprintf(stderr, "IN: %s @%d: Invalid Args\n", __FILE__, __LINE__);
}
else if(SIZE_STACK <= s.top)
{
printf("Stack Full, Can not add anymore elements\n");
}
else
{
struct myStruct* p = malloc( 1 * sizeof *p);
if(NULL == p)
{
fprintf(stderr, "IN: %s @%d: Out of Memory\n", __FILE__,
__LINE__);
}
else
{
strcpy(p->title, ele);
arr[s.top] = p;
s.top += 1;
}
}
}