How should I print StackArray in C?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct
{
void** stackAry;
int count;
int stackMax;
int top;
}STACK;
STACK* createStack(int maxSize)
{
STACK* stack;
stack = (STACK*)malloc(sizeof(STACK));
if(!stack)
return NULL;
stack->count = 0;
stack->top = -1;
stack->stackMax = maxSize;
stack->stackAry = (void**)calloc(stack->stackMax, sizeof(void*));
if(!stack->stackAry)
{
free(stack);
return NULL;
}
return stack;
}
bool pushStack(STACK* stack, void* itemPtr)
{
if(stack->count == stack->stackMax)
return false;
(stack->count)++;
(stack->top)++;
stack->stackAry[stack->top] = itemPtr;
return true;
}
void* popStack(STACK* stack)
{
void* dataPtrOut;
if(stack->count == 0)
dataPtrOut = NULL;
else
{
dataPtrOut = stack->stackAry[stack->top];
(stack->count)--;
(stack->top)--;
}
return dataPtrOut;
}
void* stackTop(STACK* stack)
{
if(stack->count == 0)
return NULL;
else
return stack->stackAry[stack->top];
}
bool emptyStack(STACK* stack)
{
return(stack->top == -1);
}
bool fullStack(STACK* stack)
{
return (stack->count == stack->stackMax);
}
int stackCount(STACK* stack)
{
return stack->count;
}
STACK* destroyStack(STACK* stack)
{
int i;
if(stack)
{
for(i=0 ; i<stack->count ; i++)
free(stack->stackAry[i]);
free(stack->stackAry);
free(stack);
}
return NULL;
}
int main(void)
{
STACK* myStack = createStack(100);
double* ptr;
while(1)
{
ptr = (double*)malloc(sizeof(double));
if(ptr == NULL)
return 0;
else
{
printf("Enter a positive real number: <-1> to stop: \n");
scanf("%lf", ptr);
if(*ptr == -1.0 || fullStack(myStack))
{
break;
}
else
pushStack(myStack, ptr);
}
}
printf("\n\nThe list of numbers reversed: \n");
while(!emptyStack(myStack))
{
ptr = (double*)popStack(myStack);
printf("%lf\n", *ptr);
free(ptr);
}
myStack = destroyStack(myStack);
return 0;
}
When I run the stackAry, the main part doesn't print.
The stack part does not seem to be a problem, but if you print it, "Enter a positive real number: <-1> to stop:" is not printed. If you enter numbers on a blank screen and press -1, it will be printed.
I'm not sure which part is wrong. Please help me
Related
I'm new to programming, while I know there are better codes out there for this question I sort of don't understand why this isn't working, the value returned by pop2() here is a part of a string which is why for %d it doesn't print the correct value but for %c it does
int n = pop2();
printf("n is now %c\n", n);
thus even numbers are of string type for s = "3[a2[c]]" I want my loop to run the number of times that is returned by pop (2 and then 3 in this case), since the value returned by pop2() is of char type even after using atoi it doesn't work
I tried doing
int n = atoi(pop2());
//or even
char* n = pop2();
int num = atoi(n);
but it still wouldn't work, here's the entire code of the function, I've typed out printf statements to help me recognize where I was going wrong, I'd be so grateful if you don't mind helping me out. Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <ctype.h>
struct node
{
int data;
struct node *link;
} *top = NULL;
struct node2
{
int data;
struct node2 *link;
} *top2 = NULL;
int isEmpty()
{
if (top == NULL)
{
return 1;
}
return 0;
}
int isEmpty2()
{
if (top2 == NULL)
{
return 1;
}
return 0;
}
int pop()
{
if (isEmpty())
{
return 0;
}
int val;
val = top->data;
top = top->link;
return val;
}
int pop2()
{
if (isEmpty2())
{
return 0;
}
int val;
val = top2->data;
top2 = top2->link;
return val;
}
void push(int data)
{
struct node *new = (struct node *)malloc(sizeof(struct node));
if (new == NULL)
{
exit(1);
}
new->data = data;
new->link = NULL;
new->link = top;
top = new;
}
void push2(int data)
{
struct node2 *new = (struct node2 *)malloc(sizeof(struct node2));
if (new == NULL)
{
exit(1);
}
new->data = data;
new->link = NULL;
new->link = top2;
top2 = new;
}
int peek()
{
if (isEmpty())
{
return 0;
}
return top->data;
}
int peek2()
{
if (isEmpty2())
{
return 0;
}
return top2->data;
}
char *decodeString(char *s, char *arr)
{
for (int i = 0; i < strlen(s); i++)
{
if (s[i] == '[')
{
printf("pushing s[i] that is %c on stack 1\n", s[i]);
push(s[i]);
}
if (isalpha(s[i]))
{
printf("pushing %c on stack 2\n", s[i]);
push2(s[i]);
}
if (isdigit(s[i]))
{
printf("pushing %c on stack 2\n", s[i]);
push2(s[i]);
}
if (s[i] == ']')
{
if (peek() == '[')
{
printf("s[i] is %c and peek element is %c \n", s[i],
peek());
printf("%c is now popped out next element in stack one is %c\n", pop(), peek());
if (isalpha(peek2()))
{
printf("element in stack 2 now is %c\n", peek2());
char ch = pop2();
printf("ch now is %c\n", ch);
strcat(arr, &ch);
printf("arr after strncating is:");
printf("%s ", arr);
printf("\n");
}
if (isdigit(peek2()))
{
printf("element in stack 2 now is %c\n", peek2());
int n = pop2();
printf("n is now %c\n", n);
printf("current arr is %s\n", arr);
while (n < 0)
{
strcat(arr, &arr);
printf("i. %d strncated %s\n", i, arr);
n--;
}
}
}
}
}
for (int i = 0; i < 10; i++)
{
printf("%c ", arr[i]);
}
printf("\n");
return arr;
}
int main()
{
char s[100] = "3[a2[c]]";
char arr[10] = {0};
decodeString(s, arr);
return 0;
}
here's the output I'm getting, sorry for making this so long
When I try to implement parenthesis problem using stack (array representation) it showing above problem. Here I use dynamic memory allocation in array. When I try to compile the above program it appear built log like : process terminated with status -1073741510 (0 minute(s), 2 second(s))
#include<stdlib.h>
struct stack
{
int size;
int top;
char *arr;
};
int parenthematch(char *pt)
{
struct stack *st;
st->size = 100;
st->top = -1;
st->arr = (char *)malloc(st->size * sizeof(char)); //create array of st->size
for(int i=0; pt[i]!='\0'; i++)
{
if(pt[i]=='(')
{
push(st,'(');
}
else if(pt[i]==')')
{
if(isEmpty(st))
{
return 0;
}
pop(st);
}
}
int main()
{
char *p ="(34)(4(5+6))";
if(parenthematch(p))
{
printf("parenthesis match \n");
}
else
{
printf("Not match");
}
return 0;
} ```
#include <stdio.h>
#include <stdlib.h>
struct stack
{
size_t size;
int top;
char *arr;
};
void push(struct stack *st, char ch)
{
st->top += 1;
st->arr[st->top] = ch;
}
int isEmpty(struct stack *st)
{
return st->top == -1;
}
void pop(struct stack *st)
{
st->top -= 1;
}
int parenthematch(char *pt)
{
struct stack *st = (struct stack *)malloc(sizeof(struct stack));
st->size = 100;
st->top = -1;
st->arr = (char *)malloc(st->size * sizeof(char)); //create array of st->size
for (int i = 0; pt[i] != '\0'; i++)
{
if (pt[i] == '(')
{
push(st, '(');
}
else if (pt[i] == ')')
{
if (isEmpty(st) || st->arr[st->top] != '(')
{
return 0;
}
pop(st);
}
}
return isEmpty(st);
}
int main()
{
char p[] = "(34)(4(5+6))";
if (parenthematch(p))
{
printf("parenthesis match \n");
}
else
{
printf("Not match");
}
return 0;
}
I am trying to implement stack with array in C. But I guess my push function is not correct.(Maybe there are some other mistakes) Because when I run the code, it prints "Stack is empty!" two times.
How can I solve this problem and is this implementation logic is true?
#include <stdio.h>
#define SIZE 10
typedef struct stack
{
int top;
int items[SIZE];
}stack;
void push(int a, stack st)
{
if((st.top + 1) != SIZE)
{
st.top++;
st.items[st.top] = a;
}
else
{
printf("\nStack is full!");
}
}
void pop(stack st)
{
if(st.top != -1)
{
st.top--;
}
else
{
printf("\nStack is empty!");
}
}
void printList(stack st)
{
int i;
for(i = 0; i < st.top + 1; i++)
{
printf("%d -> ", st.items[i]);
}
puts("");
}
int main(void)
{
stack stack1;
stack1.top = -1;
stack stack2;
stack2.top = -1;
push(3, stack1);
push(5, stack1);
push(7, stack1);
printList(stack1);
pop(stack1);
printList(stack1);
pop(stack1);
printList(stack1);
}
Hi your stack implementation is wrong.Using gdb you can verify this.You are passing structure as value you should pass as address.
On gdb you can see
In main
gdb) p &stack1
$4 = (stack *) 0x7fffffffddf0
In push fn
(gdb) p &st
$3 = (stack *) 0x7fffffffdd90
both are different.
correct code is given below.
#include <stdio.h>
#define SIZE 10
typedef struct stack
{
int top;
int items[SIZE];
}stack;
void push(int a, stack *st)
{
if((st->top + 1) != SIZE)
{
st->top++;
st->items[st->top] = a;
}
else
{
printf("\nStack is full!");
}
}
void pop(stack *st)
{
if(st->top != -1)
{
st->top--;
}
else
{
printf("\nStack is empty!");
}
}
void printList(stack *st)
{
int i;
for(i = 0; i < st->top + 1; i++)
{
printf("%d -> ", st->items[i]);
}
puts("");
}
int main(void)
{
stack stack1;
stack1.top = -1;
stack stack2;
stack2.top = -1;
push(3, &stack1);
push(5, &stack1);
push(7, &stack1);
printList(&stack1);
pop(&stack1);
printList(&stack1);
pop(&stack1);
printList(&stack1);
}
I have implemented a Stack using dynamic array(implementing array doubling) but when the doubling happens for the second time, I am getting runtime error! What's going wrong with the implementation? Please help.
#include <stdio.h>
#include <stdlib.h>
struct Stack {
int *arr;
int top,size,capacity;
};
struct Stack *createStack(int capacity) {
struct Stack *s = (struct Stack*)malloc(sizeof(struct Stack));
s->arr = (int*)malloc(sizeof(int)*capacity);
s->top = -1;
s->capacity = capacity;
s->size = 0;
return s;
}
void doubleStack(struct Stack *s) {
s->capacity = s->capacity*2;
s->arr = realloc(s->arr,s->capacity);
printf("Array doubling happened successfully!\n");
}
int isFull(struct Stack *s) {
return s->size == s->capacity;
}
void push(struct Stack *s, int item) {
if(isFull(s))
doubleStack(s);
printf("%d pushed!\n",item);
s->arr[++(s->top)] = item;
s->size++;
}
int isEmpty(struct Stack *s) {
return s->size == 0;
}
void pop(struct Stack *s) {
if(isEmpty(s)) {
printf("Empty stack!\n");
return;
}
int item = s->arr[(s->top)--];
s->size--;
printf("%d popped!\n",item);
}
int main(void) {
struct Stack *s = createStack(2);
push(s,1);
push(s,2);
push(s,3);
push(s,4);
push(s,5);
pop(s);
pop(s);
return 0;
}
You failed to multiply the size to allocate via realloc() by sizeof(int).
Try this with some other improvement:
#include <stdio.h>
#include <stdlib.h>
struct Stack {
int *arr;
int top,size,capacity;
};
struct Stack *createStack(int capacity) {
struct Stack *s = malloc(sizeof(struct Stack));
s->arr = malloc(sizeof(int)*capacity);
s->top = -1;
s->capacity = capacity;
s->size = 0;
return s;
}
void destroyStack(struct Stack *s) {
if(s != NULL) free(s->arr);
free(s);
}
void doubleStack(struct Stack *s) {
s->capacity = s->capacity*2;
s->arr = realloc(s->arr,sizeof(int)*s->capacity);
if(s->arr != NULL) {
printf("Array doubling happened successfully!\n");
} else {
perror("realloc");
}
}
int isFull(struct Stack *s) {
return s->size == s->capacity;
}
void push(struct Stack *s, int item) {
if(isFull(s))
doubleStack(s);
printf("%d pushed!\n",item);
s->arr[++(s->top)] = item;
s->size++;
}
int isEmpty(struct Stack *s) {
return s->size == 0;
}
void pop(struct Stack *s) {
if(isEmpty(s)) {
printf("Empty stack!\n");
return;
}
int item = s->arr[(s->top)--];
s->size--;
printf("%d popped!\n",item);
}
int main(void) {
struct Stack *s = createStack(2);
push(s,1);
push(s,2);
push(s,3);
push(s,4);
push(s,5);
pop(s);
pop(s);
destroyStack(s);
return 0;
}
I am trying to create a program to convert an infix expression to post fix and evaluate it using a stack. The three files are below. When I run the code I get a segmentation fault. The debugger in Xcode says that it occurs between the push and the two pop calls in the middle file in the evaluate_postfix function. Can anyone help me with why this is seg faulting?
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
stack* create_stack(void)
{
stack* newPtr = malloc(sizeof(stack));
newPtr->size = 0;
newPtr->stack = NULL;
return newPtr;
}
void push(stack *s, int val)
{
node* newPtr = (node*) malloc(sizeof(node));
newPtr->data = val;
newPtr->next = s->stack;
s->stack = newPtr;
s->size++;
}
void pop(stack *s)
{
node* newPtr = NULL;
node* tempPtr = NULL;
tempPtr = s->stack;
newPtr = tempPtr->next;
free(tempPtr);
s->stack = newPtr;
s->size--;
}
int top(stack *s)
{
int num;
node* newPtr = NULL;
newPtr = s->stack;
num = newPtr->data;
return num;
}
int isEmpty(stack *s)
{
if(s->stack == NULL)
{
return 1;
}
else
{
return 0;
}
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "stack.h"
#include <string.h>
#define MAX_EQU_LEN 100
static int prec(char operator)
{
switch (operator)
{
case '*':
return 5;
case '/':
return 4;
case '%':
return 3;
case '+':
return 2;
case '-':
return 1;
default:
break;
}
return 0;
}
static int isNumeric(char* num)
{
if(atoi(num) == 0)
{
return 0;
}
return 1;
}
char* infix_to_postfix(char* infix)
{
int i,a=0;
char* postfix = malloc(MAX_EQU_LEN);
stack* s = create_stack();
for(i=0;infix[i]!='\0';i++){
if(!isNumeric(&((infix[i]))))
{
postfix[a]=infix[i];
a++;
}
else if(isEmpty(s))
push(s,infix[i]);
else if(prec(infix[i])>prec(s->stack->data))
push(s,infix[i]);
else
{
postfix[a]=s->stack->data;
a++;
pop(s);
if(!isEmpty(s)){
while(prec(s->stack->data)<= prec (infix[i]))
{
postfix[a]=s->stack->data;
a++;
pop(s);
}
}
else
push(s,infix[i]);
}
}
return postfix;
}
int evaluate_postfix(char* postfix) {
int i,result = 0;
int right = 0, left = 0;
char* token = NULL;
stack* s = create_stack();
s->size = strlen(postfix);
node* tempPtr = NULL;
for(i = 0; i < s->size ; i++)
{
token = strtok(postfix, " ");
if(isNumeric(token) == 1)
{
atoi(token);
push(s, *token);
}
else
{
left = tempPtr->data;
pop(s);
right = tempPtr->data;
pop(s);
switch(*token)
{
case '+':
result = left + right;
break;
case '-':
result = left - right;
break;
case '*':
result = left * right;
break;
case '/':
result = left / right;
break;
case '%':
result = left % right;
break;
}
push(s, result);
}
strtok(NULL, " ");
}
return result;
}
#include <stdio.h>
#include <string.h>
#include "calculator.h"
#define BUFFERSIZE 100
int main(int argc, char* argv[]) {
char buffer[BUFFERSIZE];
if (argc != 2) {
printf("correct ussage: %s <input file>\n", argv[0]);
return 1;
}
FILE* fp = fopen(argv[0], "r");
if(fp == NULL) {
printf("unable to open file: %s\n", argv[1]);
return 1;
}
while(fgets(buffer, BUFFERSIZE, fp)) {
if (buffer[strlen(buffer)-1] == '\n') {
buffer[strlen(buffer)-1] = '\0';
}
char *postfix = infix_to_postfix(buffer);
int result = evaluate_postfix(postfix);
printf("%s = %d\n", buffer, result);
}
return 0;
}
Each call to strtok() that doesn't contain a NULL pointer as its first argument resets the internal pointer of the strtok() function to the beginning of the string.
At the beginning of the loop in your int evaluate_postfix(char* postfix); function, you call
token = strtok(postfix, " ");
Which means that at the beginning of the loop, token ALWAYS pointers to the first non-space character at the beginning of postfix. So each loop it would see an operator, and try to pop() two values from the stack. But your stack would quickly deplete, and the stack will begin to point to garbage data (s->size < 0).
token = strtok(postfix, " ");
for(i = 0; i < s->size ; i++)
{
....
token = strtok(NULL, " ");
}
Should fix your issue.