将链接列表转换为字符数组

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

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

但是输出是这个-

我不确定为什么要得到这个输出。任何建议,将不胜感激

c arrays linked-list
2个回答
0
投票

根据问题下的注释,代码中存在两个问题:

  1. printf正在打印指针的地址,而不是字符串本身。 printf应该是printf("%s\n", result);
  2. 字符串的元素需要转换为字符'0''1'。这可以通过将'0'添加到字符串的每个元素来完成,例如result[i] = temp->bit + '0';

-1
投票

如果我错了,请纠正我,但这里有两个问题:

  • 您创建了一个计数变量,但从未使用过。

  • 您将结果作为指针启动,但将其用作数组。代替result[i],应该是*(result + i)

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