【题目描述】
输入学生人数n,再输入n个学生姓名,然后将学生姓名升序排序,要求使用指针数组和动态内存分配函数malloc来存放多个字符串。
【输入形式】
第一行输入学生人数n(2≤n≤20)。
接下来n行,每行一个字符串,表示学生的姓名,学生的姓名长度不超过30,并且学生姓名不包含空格。
【输出形式】
n行,每行一个字符串,表示升序排序后学生的姓名。
【样例输入】
4
Huangcaiyan
Maihaidong
Luye
Lifugao
【样例输出】
Huangcaiyan
Lifugao
Luye
Maihaidong
#include<stdio.h>
#include<iostream>
#include<cstring>
#include<malloc.h>
using namespace std;
int main()
{
int n;
cin>>n;
int *p=NULL;
p=(int *)malloc(n*sizeof(int));//动态数组
if(p=NULL) {
cout<<"no enough mrmory"<<endl;
exit(0);
}
for(int i=0;i<=n;i++)//输入n个名字
{
cin>>*(p+i);
}
for(int i=0;i<n;i++)//按照字典升序排序
{
for(int j=0;j<n-1;j++)
{
if(strcmp (*(p+i),*(p+i+1))>0)
{
int t=*(p+i);
*(p+i)=*(p+i+1);
*(p+i+1)=t;
}
}
}
for(int i=0;i<n;i++)//输出排序后的名字
{
cout<<*(p+i)<<endl;
}
free(p);//释放空间
return 0;
}
int *p=NULL;就不合适,名字需要字符类型,
c++用string类型更方便。
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
//int* p = NULL;
string * p = new string[n]();//p = (int*)malloc(n * sizeof(int));//动态数组
if(p==NULL)//if (p = NULL) {
{
cout << "no enough mrmory" << endl;
return 1; //exit(0); //一般返回值0表示正常返回,其他表示出错返回
}
for (int i = 0; i < n; i++)//for (int i = 0; i <= n; i++)//输入n个名字
{
cin >> *(p + i);
}
for (int i = 0; i < n; i++)//按照字典升序排序
{
for (int j = 0; j < n-1; j++)
{
if((*(p + i)).compare(*(p + j))<0)//if (strcmp(*(p + i), *(p + i + 1)) > 0)
{
(*(p + i)).swap(*(p + j)); //直接使用string的交换函数
//int t = *(p + i);
//*(p + i) = *(p + i + 1);
//*(p + i + 1) = t;
}
}
}
for (int i = 0; i < n; i++)//输出排序后的名字
{
cout << *(p + i) << endl;
}
delete[] p; //free(p);//释放空间
return 0;
}
题主代码修改如下,供参考:
#include<stdio.h>
#include<iostream>
#include<cstring>
#include<malloc.h>
using namespace std;
int main()
{
int n,i;
char **p,t[30]={0};
cin>>n;
p=(char **)malloc(n*sizeof(char));//动态数组
if(p==NULL) {
cout<<"no enough mrmory"<<endl;
exit(0);
}
for(i=0;i<n;i++)
p[i] = (char*)malloc(30*sizeof(char));
for(int i=0;i < n;i++)//输入n个名字
{
cin>>*(p+i);
}
for(int i=0;i<n-1;i++)//按照字典升序排序
{
for(int j=0;j<n-1-i;j++)
{
if(strcmp (p[j],p[j+1])>0)
{
strcpy(t,*(p+j));
strcpy(*(p+j),*(p+j+1));
strcpy(*(p+j+1),t);
}
}
}
for(int i=0;i<n;i++)//输出排序后的名字
{
cout<<*(p+i)<<endl;
}
for(i=0;i<n;i++)
free(p[i]);//释放空间
free(p);
return 0;
}