gpt4 book ai didi

c - 使用 malloc 时对字符串进行排序

转载 作者:行者123 更新时间:2023-11-30 16:24:45 25 4
gpt4 key购买 nike

如何在不破坏程序的情况下对字符串进行排序?字符串输入必须在不使用 gets(fgets , getsc 等)的情况下完成

int main ()
{

char **pointsarr;
char temp;

printf("insert strings: \n");
scanf("%d",&a);
printf("declare the size of the strings: \n");

pointsarr = malloc(a * sizeof(char*));



for (i=0; i<a; i++)
{

pointsarr[i]= malloc(b* sizeof(char));
}

printf("input strings: \n");

for (i=0; i<a; i++)
{
scanf("%s", pointsarr[i]);
}

printf("the strings on the 2d board: \n");

for (int i=0; i<a; i++)
printf("%s\n",pointsarr[i]);

/* int n= strlen(pointsarr);

for (i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if (pointsarr[i]>pointsarr[j])
{
temp=pointsarr[i];
temp=pointsarr[i]; // whats going wrong on this point?
pointsarr[i]=pointsarr[j];
pointsarr[j]=temp;
}
}
}
*/

free(pointsarr);



}

如果出了什么问题并且它不返回排序后的字符串?

最佳答案

对数组进行排序的最简单方法是使用库函数 qsort()

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int comparefunc (const void* p1, const void* p2)
{
return strcmp (* (const char **) p1, * (const char **) p2);
}

int main ()
{
int i, a = 4, b = 20;
char **pointsarr = (char **) malloc(a * sizeof(char*));

for (i=0; i<a; i++)
pointsarr[i]= (char *) malloc(b* sizeof(char));

strcpy (pointsarr [0], "qwerty");
strcpy (pointsarr [1], "uiop");
strcpy (pointsarr [2], "asdf");
strcpy (pointsarr [3], "ghjkl");

for (i=0; i<a; i++)
printf("%s\n",pointsarr[i]);
printf("-----\n");

qsort (pointsarr, a, sizeof (char **), comparefunc);

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

输出:

qwerty
uiop
asdf
ghjkl
-----
asdf
ghjkl
qwerty
uiop

Live demo

关于c - 使用 malloc 时对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53582478/

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