gpt4 book ai didi

c - 将字符串从结构传递到字符串数组 - C

转载 作者:太空宇宙 更新时间:2023-11-04 02:49:33 25 4
gpt4 key购买 nike

typedef struct mensagem
{
int sender ;
int receiver ;
char *text ;
} *Item ;

typedef struct node
{
Item item ;
struct node *next ;
} *link ;

typedef struct queue
{
link head, tail ;
int size ;
} *Queue ;

void listsorted(Queue list)
{
Queue temp = list ;
int s=temp->size ;
char *sorted ;
int i=0;

sorted = (char*) malloc(sizeof(char));

while ( i < s )
{
strcpy( sorted[i] , list->head->item->text ) ;
list->head = list->head->next ;
i++ ;
}

i=0;

for ( i=0 ; i<s ; i++ )
{
printf("%s\n", sorted[i] ) ;
}
}

我想按字母顺序对队列进行排序,所以我想将字符串复制到一个数组中,然后对该数组进行排序。但我什至没有设法用字符串制作数组。我在 strcpy 上收到错误。我究竟做错了什么?

最佳答案

您没有对数组的两个维度进行 malloc()。看看下面的代码(未经测试):

 void listsorted(Queue list)
{
Queue temp = list ;
int s=temp->size ;
char **sorted ; /* Changed here */
int i=0;

sorted = malloc((s + 1) * sizeof(char *)); /* Changed here */

while ( i < s )
{
sorted[i] = malloc(strlen(list->head->item->text) + 1); /* Changed here */
strcpy( sorted[i] , list->head->item->text ) ;
list->head = list->head->next ;
i++ ;
}
sorted[i] = NULL; /* Changed here. NULL terminate array */

i=0;

for ( i=0 ; i<s ; i++ )
{
printf("%s\n", sorted[i] ) ;
}
}

关于c - 将字符串从结构传递到字符串数组 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23611747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com