字符串排序解决办法
字符串排序
输入5个城市名,用字符串排序。
#include <stdio.h>
#include <string.h>
void main()
{
char *city[5] = { "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 " };
char *temp;
printf( "\n 请输入5个城市名:\n ");
for(int i = 0; i < 5; i++)
{
gets(city[i]);
}
printf( "\n\n 排序前的顺序是:\n ");
for(i = 0; i < 5; i++)
{
printf( "%s\n ", city[i]);
}
for(i = 1; i < 5; i++)
{
for(int j = 0; j < 5-i; j++)
{
if( strcmp(city[j], city[j+1]) > 0 )
{
temp = city[j];
city[j] = city[j+1];
city[j+1] = temp;
}
}
}
printf( "\n\n 排序后的顺序是:\n ");
for(i = 0; i < 5; i++)
{
printf( "%s\n ", city[i]);
}
}
我通过了编译和链接,就是程序运行的时候输入完一个字符串敲回车后就出现了错误,调试发现是( Access Violation)。
请指教错在哪里!!!
------解决方案--------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
/* char *city[5] = { "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 " }; */
char *city[5];
char *temp;
for (int i=0; i <5; i++)
city[i] = (char *)malloc(10);
printf( "\n 请输入5个城市名:\n ");
for(i = 0; i < 5; i++)
{
gets(city[i]);
}
printf( "\n\n 排序前的顺序是:\n ");
for(i = 0; i < 5; i++)
输入5个城市名,用字符串排序。
#include <stdio.h>
#include <string.h>
void main()
{
char *city[5] = { "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 " };
char *temp;
printf( "\n 请输入5个城市名:\n ");
for(int i = 0; i < 5; i++)
{
gets(city[i]);
}
printf( "\n\n 排序前的顺序是:\n ");
for(i = 0; i < 5; i++)
{
printf( "%s\n ", city[i]);
}
for(i = 1; i < 5; i++)
{
for(int j = 0; j < 5-i; j++)
{
if( strcmp(city[j], city[j+1]) > 0 )
{
temp = city[j];
city[j] = city[j+1];
city[j+1] = temp;
}
}
}
printf( "\n\n 排序后的顺序是:\n ");
for(i = 0; i < 5; i++)
{
printf( "%s\n ", city[i]);
}
}
我通过了编译和链接,就是程序运行的时候输入完一个字符串敲回车后就出现了错误,调试发现是( Access Violation)。
请指教错在哪里!!!
------解决方案--------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
/* char *city[5] = { "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 ",
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 " }; */
char *city[5];
char *temp;
for (int i=0; i <5; i++)
city[i] = (char *)malloc(10);
printf( "\n 请输入5个城市名:\n ");
for(i = 0; i < 5; i++)
{
gets(city[i]);
}
printf( "\n\n 排序前的顺序是:\n ");
for(i = 0; i < 5; i++)