2009xyz 2021-06-01 12:10 采纳率: 100%
浏览 58
已采纳

C语言为什么输出出栈的字符串时会输出乱码如0xz,是因为没有正确分配内存吗?希望大佬们解答

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct LLNode
{
    char ID[5];
    struct LLNode *next;
};

struct LLNode * createNode(char val[5]) 
{
    struct LLNode *temp;
    temp=(struct LLNode *)malloc(sizeof(struct LLNode));
    temp->next=NULL;
    strcpy(temp->ID, val);
    return temp;
};

void push(char* val, struct LLNode *head)
{
    struct LLNode *temp;
    temp = createNode(val);
    temp->next = head->next;
    head->next = temp;
}

char* pop(struct LLNode *head)
{
    struct LLNode *temp;
    char *val = (char *)malloc(5*sizeof(char));
    strcpy(head->next->ID, val);
    temp = head->next;
    head->next = head->next->next;
    free(temp);
    return val;
}

char nothing(struct LLNode *head, struct LLNode *tail)
{
    if(head->next == NULL) 
        return 1;
    else
        return 0;
}

int main()
{
    char* value = (char *)malloc(5*sizeof(char));
    struct LLNode *head = NULL;
    struct LLNode *tail = NULL;

    head = createNode("");
    tail = createNode("");

    head->next = tail;
    printf("head->ID = %s\n", head->ID);

    push ("C201", head);
    printf("head->next->ID = %s\n",head->next->ID) ;  

    push ("C202", head);
    printf("head->next->ID = %s\n",head->next->ID) ;  

    push ("C203", head);
    printf("head->next->ID = %s\n",head->next->ID) ;  

    push ("C204", head);
    printf("head->next->ID = %s\n",head->next->ID) ;  

    push ("C205", head);
    printf("head->next->ID = %s\n",head->next->ID) ;  
    
    for (int i=0; i<3; i++)
    {
        value = (char *)malloc(5*sizeof(char));
        strcpy(value, pop(head));
        printf("The value pop = %s\n", value);
        printf("head->next->ID= %s\n",head->next->ID);
        free(value);
    }
    
    if (nothing(head,tail))
        printf("The stack is empty");

    printf("Remaining IDs:");
    struct LLNode *curr = head;
    while (curr) 
    {
        printf("%s ",curr->ID);
        curr = curr->next;
    }
    return 0;
}

输出:

 

  • 写回答

4条回答 默认 最新

  • 胖哥王老师 单片机领域新星创作者 2021-06-01 12:27
    关注
    char* pop(struct LLNode *head)
    {
        struct LLNode *temp;
        char *val = (char *)malloc(5*sizeof(char));
        //strcpy(head->next->ID, val);
    	
        strcpy( val,head->next->ID);
        temp = head->next;
        head->next = head->next->next;
        free(temp);
        return val;
    }

    拷贝反了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作