在 C 中创建字符串链表

问题描述 投票:0回答:1

所以我想在c中制作一个十六进制到二进制的转换函数,我的实现计划是将十六进制中的字符更改为一串二进制数字 将字符数组字符串放入链表中 并打印出所述链表 但是,当我运行它时,它会出现段错误,并且考虑到它是在汇编中,我真的不知道如何使用 gdb 进行调试 因此有人可以指出我哪里出错了吗?

#include <stdio.h>
#include <stdlib.h>
#include "h2b.h"

int main(int argc, char* argv[])
{
    for (int i=1; i<argc; i++){
        hexToBinary(argv[i]);
        printf("\n");
    }
    return 0;
}

typedef struct hexString{
    char* data;
    struct hexString* next;
}hexString;


hexString* head= NULL;

void add(char* bits, hexString* ptr){
    hexString* temp = (hexString*)malloc(sizeof(hexString));
    temp->data = bits;
    temp->next = NULL;
    if(head == NULL){
            head = temp;
    }
    else{
            ptr = head;
            while(ptr->next != NULL){
                ptr = ptr->next;
            }
            ptr->next=temp;
    }
    free(temp);
}

void display(hexString* ptr){
    if (head==NULL){
        printf("There is nothing here");
    }
    else{
        hexString* ptr;
        while(ptr != NULL){
            printf("%s", ptr->data);
        }
        ptr = ptr->next;
    }
}


char* H2B_MAP(char hex){
    switch(hex){
        case'0':
            return "0000";
        case'1':
            return "0001";
        case '2':
            return "0010";
        case '3':
            return "0011";
        case '4':
            return "0100";
        case '5':
            return "0101";
        case '6':
            return "0110";
        case '7':
            return "0111";
        case '8':
            return "1000";
        case '9':
            return "1001";
        case 'A':
        case 'a':
            return "1010";
        case 'B':
        case 'b':
            return "1011";
        case 'C':
        case 'c':
            return "1100";
        case 'D':
        case 'd':
            return "1101";
        case 'E':
        case 'e':
            return "1110";
        case 'F':
        case 'f':
            return "1111";
    }
}

int hexToBinary(char* hex){ //no need for 0x formatting
    hexString x;
    hexString* x_ptr =&x;
    for(int i=0; i<sizeof(hex); i++){ //internally it is a linked list storing strings so how would you do that, ie convert each number into a different number
        add(H2B_MAP(hex[i]), x_ptr);
    }
    display(x_ptr);
    return 0;
}


c pointers linked-list
1个回答
0
投票

在保留指向该块的引用后,您将释放内存!删除对

free()
的呼叫。

© www.soinside.com 2019 - 2024. All rights reserved.