When I try to printf the value, which is a string, it does fine when it is in the push() function but when I run the same command in the main function, it prints garbage. For example if I enter A for the prompt "Enter Value of number: ", I get A printed in the push() but garbage like ?P( from the main function.
struct v
{
char *value;
int ibase;
int obase;
struct v* next;
};
struct v* top = NULL;
void push(char* val, int ibas, int obas)
{
struct v* newstackptr=malloc(sizeof(*newstackptr));
newstackptr->next = top;
newstackptr->value= val;
printf("%s",val);//<-prints just fine
printf("\n%s", newstackptr->value);//<-prints just fine
newstackptr->ibase= ibas;
newstackptr->obase= obas;
top = newstackptr;
printf("\n%s", top->value);//<-prints just fine
}
void getUserInput(){
int ibase,obase;
printf("Enter Value of number: ");
char value[20];
scanf("%s",value);
printf("\nEnter the initial base: ");
scanf("%d",&ibase);
printf("\nEnter the output base: ");
scanf("%d",&obase);
printf("\n");
push(value,ibase,obase);
}
char* getValue(){
return top->value;
}
int main(){
getUserInput();
printf("%s",top->value);//<-this returns garbage
printf("%s",getValue());//<-this returns garbage
return 0;
}