【发布时间】: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