i'm studying a data structure. Now i have tried to write some stack by language C, unfortunately unsuccessfully.
In case 4 in switch statement i have an error like this: Exception thrown: read access violation.
What there can be an error?
Here is my code:
int main(int argc, char** argv)
{
int size;
int element;
printf("enter the size of stack: ");
scanf("%d", &size);
uint32_t* arr = malloc(sizeof(uint32_t) * size);
stack_t structure= { arr, size, 0};
int check = 1;
while (check == 1)
{
int op;
int condition;
printf("Enter the action: 1) check stack for empty; 2) push function; 3) pop function; 4) print stack\n");
printf("Command: ");
scanf("%d", &op);
printf("\n");
switch (op)
{
case 1:
structure.empty = stack_empty(&structure);
break;
case 2:
printf("enter the number to be pushed: ");
scanf("%d", &element);
push(&structure, element);
break;
case 3:
structure.stack = pop(&structure);
break;
case 4:
for (int i = 0; i < structure.size; i++)
printf("[%d] = %d\n", i, structure.stack[i]);
break;
default:
printf("The command is not found, try again\n");
break;
}
printf("Continue? y/n(1/0)\n");
scanf("%d", &condition);
check = condition;
}
system("pause");
return 0;
}
Here is functions who's probably may not work correctly
typedef struct stack
{
uint32_t* stack;
int size;
uint8_t top;
uint8_t empty;
}stack_t;
int stack_empty(stack_t* s)
{
if (s->top == 0)
return 1;
else
return 0;
}
void push(stack_t* s, uint8_t element)
{
s->top = s->top + 1;
s->stack[s->top] = element;
}
int pop(stack_t* s)
{
if (stack_empty(s))
{
printf("stack is underflow\n");
exit(1);
}
else
{
s->top = s->top - 1;
return (s->stack[s->top + 1]);
}
}
(uint32_t)malloc(...)Your compiler should have given you a strong warning/error about assigning an integer type to a pointer. Don't ignore those warnings. Fix them before posting here. In this case, the correct cast would be(uint32_t *), but you should just get rid of the cast entirely, it's not needed. But by casting the pointer to an integer, if your pointer is larger than 32 bits, it is destroyed by the cast.if (stack_empty(&s))should beif (stack_empty(s)).sis already a pointer, so you want to pass its value, not its address.element,underflow,overflowandemptyshould not be part of the stack structure.