[英]Passing a string from a structure to an array of strings - C
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] ) ;
}
}
我想按字母顺序对队列进行排序,因此我想将字符串复制到数组并对该数组进行qsort。 但是我什至没有用字符串来制作数组。 我在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] ) ;
}
}
sorted[i]
是char类型,而不是char *类型。 那是因为您只分配一个一维数组(即字符串),而不是二维数组(即字符串数组)。 此外,你malloc
荷兰国际集团字节,然后尝试的内容复制list->head->item->text
到它。 即使您可以编译此代码,这也将是个坏消息。
确保始终分配正确的内存量,并确保始终使用strncpy
而不是strcpy
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.