C 将链表转换为字符数组

C 将链表转换为字符数组,c,arrays,linked-list,C,Arrays,Linked List,我用C写下了这段代码,以转换一个链表,其中每个节点都包含一个字符,并将该链表转换为字符串。这是我的密码 struct node { unsigned char bit : 1; struct node *next; }; //Converts the linked list into a String char *list_to_bitstring( struct node *head ) { struct node *countNode = head;

我用C写下了这段代码,以转换一个链表,其中每个节点都包含一个字符,并将该链表转换为字符串。这是我的密码

struct node {
    unsigned char bit : 1;
    struct node *next;
};
   //Converts the linked list into a String 
char *list_to_bitstring( struct node *head ) {
    struct node *countNode = head;
    int count = 0;//Counts number of nodes
    while ( countNode != NULL ) {
        count++;
        countNode = countNode->next;
    }
    char *result = (char *)malloc( sizeof( count + 1 ) );
    struct node *temp = head;
    int i = 0;
    while ( temp != NULL ) {
        result[i] = temp->bit;
        i++;
        temp = temp->next;
    }
    result[i] = '\0';
    return result;
}

//main method
int main() {
    struct node *head1 = bitstring_to_list( "111" ); //Converts a String into a linked list 
    char *result = list_to_bitstring( head1 );
    printf( "%s", &result );
    return 0;
}
但结果是这样的-


我不知道为什么我会得到这个输出。如果您有任何建议,我们将不胜感激。

根据问题下的评论,代码中有两个问题:

  • printf
    打印的是指针的地址,而不是字符串本身。
    printf
    应该是
    printf(“%s\n”,结果)
  • 字符串的元素需要转换为字符
    '0'
    '1'
    。这可以通过向字符串的每个元素添加
    '0'
    来实现,例如
    result[i]=temp->bit+'0'

  • 请使用适当的缩进设置代码的格式,使其可读。我没有检查函数调用的准确性(使用调试器),但您应该使用
    printf(“%s”,result)
    而不是
    printf(“%s”,和result)
    <代码>结果
    已经是
    字符*
    &result
    不是字符串的地址。它是指向字符串的指针的地址。我使用printf(“%s”,result)而不是(“%s”,&result),得到了-。它就像3个盒子,里面有0和1,但由于某种原因,当我将它粘贴到这里时,它没有显示出来,这不会使
    printf(“%s”,result)
    出错。这意味着至少有一个函数工作不正常。@user3386109正常工作。谢谢