【问题标题】:Convert a linked list to an array of characters将链表转换为字符数组
【发布时间】:2020-04-17 01:50:14
【问题描述】:

我用 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("%s", result) 而不是printf("%s", &result)result 已经是 char *&result 不是字符串的地址。它是指向字符串的指针的地址。
  • 我使用 printf("%s", result) 而不是 ("%s", &result) 并且我得到了这个 - 。这就像 3 个盒子,里面有 0 和 1,但是当我出于某种原因将它粘贴到这里时它没有显示出来
  • 这不会使printf("%s", result) 错。这意味着您的至少一项功能无法正常工作。
  • @user3386109 成功了。谢谢!

标签: c arrays linked-list


【解决方案1】:

从问题下的cmets来看,代码有两个问题:

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

【讨论】:

    猜你喜欢
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多