hello friends I was writing a small program on stacks in which i used a pointer to an array to point the elements.Now I have used malloc and realloc function to allocate memory spaces and free function to deallocate. By using free function I want to deallocate one element of the array for pop() function.But the compile error shows that - "invalid conversion from int to void*".
So whether free function cannot be used to deallocate single element of a dynamically allocated array by pointer, although i found that we can free individual element of an array declared explicitly without dynamic memory allocation.This was the program although I can't say if this program is totally logically correct.
SO what is the possible way in this program to use free() function for an individual element??
Code:
#include<stdio.h>
#include<stdlib.h>
void push(int x);
void pop();
int top=-1;
int *stack;
int main()
{
int resp;
int val;
while(1){
printf("\n\nFOR PUSH PRESS 1 OR FOR POP PRESS 2\n");
scanf("%d",&resp);
switch(resp)
{
case 1:
printf("\nVALUE TO BE PUSHED IN STACK:\t");
scanf("%d",&val);
push(val);
break;
case 2:
pop();
break;
default:
printf("\nINVALID RESPONSE");
break;
}
label:
printf("\n\nDo you want to continue again:\n");
printf("\nPRESS 1 FOR YES or 0 FOR NO\n");
scanf("%d",&resp);
if(resp==1)
;
else if(resp==0)
break;
else{ printf("\nINVALID RESPONSE");
goto label;
}
}
return 0;
}
void push(int x)
{
if(top==-1)
top=1;
else
top++;
if(top==1)
stack=(int*)malloc(sizeof(int));
else
stack=(int*)realloc(stack,top * sizeof(int));
stack[top-1]=x;
return;
}
void pop()
{
if(top==-1)
{
printf("\nSTACK IS EMPTY-CANNOT DELETE\n");
return;
}
else
{
top--;
free(stack[top]);
}
}
.