首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

字符串排序解决办法

2012-02-04 
字符串排序输入5个城市名,用字符串排序。#includestdio.h#includestring.hvoidmain(){char*city[5]{\

字符串排序
输入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++)


{
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]);
}
}
[解决办法]
#include <stdio.h>
#include <string.h>
void main()
{
char *city[5];
char *temp;

printf( "\n 请输入5个城市名:\n ");

for(int i = 0; i < 5; i++)
{
city[i] = new char[100];
gets(city[i]);
}

printf( "\n\n 排序前的顺序是:\n ");
for(int i = 0; i < 5; i++)
{
printf( "%s\n ", city[i]);
}

for(int 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(int i = 0; i < 5; i++)
{
printf( "%s\n ", city[i]);
}
}


就加了一步分配内存
city[i] = new char[100];

热点排行