用于字符串的C printf打印垃圾。为什么?

时间:2018-02-20 21:20:20

标签: c printf

当我尝试printf值,这是一个字符串时,它在push()函数中运行正常,但是当我在main函数中运行相同的命令时,它会打印垃圾。例如,如果我输入A作为提示"输入数字值:",我在push()中打印A但是垃圾就像?P(来自主函数。

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;
}

0 个答案:

没有答案