gpt4 book ai didi

c - 尝试按 ASCII 值升序比较二维数组中的字符串

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

我需要从用户输入字符串并按 ascii 值的升序排列它们。谁能帮助我哪里错了?我收到错误

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

int sort(char[10][10]);

main(int argc, char *argv[])
{
int i,j,length,fun;
char c;
char a[10][10];
printf("Please enter ten strings : \n");
for(i=0;i<10;i++)
{
j=-1;
while(a[i][j]!='\n'&&j<10)
{
scanf("%c",&a[i][++j]);
}
a[i][j]='\0';
}

for(i=0;i<10;i++)
{
printf("\n");
for(j=0;j<10,a[i][j]!='\0';j++)
{
printf("a[%d][%d]=%c\n",i,j,a[i][j]);
}
}
fun=sort(a[10][10]);
return 0;
}

int sort(char s[10][10])
{
int i,j;
char temp[10];
for (i = 1; i < 10; i++) {
for (j = 1; j < 10; j++) {
if (strcmp(s[j - 1], s[j]) > 0)
{
strcpy(temp, s[j - 1]);
strcpy(s[j - 1], s[j]);
strcpy(s[j], temp);
}
}
}
printf("Sorted list(in ascending order is:");
for(i=0;i<10;i++)
{
for(j=0;j<10,s[i][j]!='\0';j++)
{
printf("%c\n",s[i][j]);
}
}
return 0;
}

最佳答案

问题:

  1. 这个:

    j=-1;

    应该是

    j = 0;

    因为数组索引从零开始,而不是-1。

  2. 这个:

    while(a[i][j]!='\n'&&j<10)

    应该是

    while(a[i][j] != '\n' && j < 9)

    这样,如果用户输入超过 9 个字符,NUL 终止符就不会写入无效的内存位置。

  3. 这个:

    fun=sort(a[10][10]);

    应该是

    fun = sort(a);

    因为您要将数组发送到函数。

关于c - 尝试按 ASCII 值升序比较二维数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676416/

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