题目如下:
请用指针数组编程实现按奥运会参赛国国名,在字典中的顺序对其入场次序进行排序。
假设参赛国不超过150个。
我的代码:
#include
#include
#define MAX_LEN 10
#define N 150
void SortString(char *ptr[], int n);
int main()
{
int i, n;
char *pStr[N];
printf("How many countries?\n");
scanf("%d", &n);
getchar();
printf("Input their names:\n");
for (i = 0; i < n; i++)
{
gets(pStr[i]);
}
SortString(pStr, n);
printf("Sorted results:\n");
for (i = 0; i < n; i++)
{
puts(pStr[i]);
}
return 0;
}
void SortString(char *ptr[], int n)
{
int i, j;
char temp;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(ptr[j] , ptr[i]) < 0 )
{
strcpy(temp , ptr[i]);
strcpy(ptr[j] , ptr[i]);
strcpy(ptr[j] , temp);
}
}
}
}
错地方不少都给你注释了,好好看看吧:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 10
#define N 150
void SortString(char *ptr[], int n);
int main()
{
int i, n;
char *pStr[N];
printf("How many countries?\n");
scanf("%d", &n);
if (n> N)//输入n值判断
{
printf("n greater than 150\n");
return 0;
}
getchar();
for (i = 0; i < n;i++)//动态分配
{
pStr[i] = (char *)malloc(32);
}
printf("Input their names:\n");
for (i = 0; i < n; i++)
{
gets(pStr[i]);
}
SortString(pStr, n);
printf("Sorted results:\n");
for (i = 0; i < n; i++)
{
puts(pStr[i]);
}
for (i = 0; i < n; i++)//释放资源
{
free(pStr[i]);
}
return 0;
}
void SortString(char *ptr[], int n)
{
int i, j;
char temp[32];
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(ptr[j], ptr[i]) < 0)
{
strcpy(temp, ptr[i]);
strcpy(ptr[i], ptr[j]);//序号反了
strcpy(ptr[j], temp);
}
}
}
}
楼上答错了,char * temp只是个指针,没有分配空间,应改为char temp[255]; 或者申请动态内存char * temp = (char *)malloc(255);
另char *pStr[N];也需要改成char pStr[N][MAX_LEN];
完整代码,VC6.0测试通过:
#include
#include
#define MAX_LEN 10
#define N 150
void SortString(char ptr[N][MAX_LEN], int n);
int main()
{
int i, n;
char pStr[N][MAX_LEN];
printf("How many countries?\n");
scanf("%d", &n);
getchar();
printf("Input their names:\n");
for (i = 0; i < n; i++)
{
gets(pStr[i]);
}
SortString(pStr, n);
printf("Sorted results:\n");
for (i = 0; i < n; i++)
{
puts(pStr[i]);
}
return 0;
}
void SortString(char ptr[N][MAX_LEN], int n)
{
int i, j;
char temp[MAX_LEN];
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(ptr[j] , ptr[i]) < 0 )
{
strcpy(temp , ptr[j]);
strcpy(ptr[j] , ptr[i]);
strcpy(ptr[i] , temp);
}
}
}
}
测试:
How many countries?
5
Input their names:
ddgsert
cgdfdg
efhjrtu
ahtert
bretwe
Sorted results:
ahtert
bretwe
cgdfdg
ddgsert
efhjrtu
void SortString(char *ptr[], int n) 函数体中的 tmpe应该是字符指针类型:
即 char temp 改为 char * temp