c动态内存分配:动态分配内存

最近学习动态分配内存
这个程序是我自己编的,呵呵,好有成就感啊...

#include <stdio.h>/*Feng原创...*/
#define N 2
char *GetCity(void);
void SortCity(char *city[]);
main()
{
char *p[N]={0};
int i,j; /*控制循环的变量*/
for (i=0;i<N;i++)
{
p=GetCity();
puts(p);
} /*动态输入城市名字*/
SortCity(p); /*排序城市*/
printf("---------------------\n");
printf("The City After Sort:\n");
printf("---------------------\n");
for (i=0;i<N;i++)
{
printf("%s \n",p);
}
getch(); /*打印城市排名*/
}
/*
函数入口:无
函数输出:指针类型地址
函数功能:动态输入城市的名字
*/
char *GetCity(void)
{
int i=0;
char ch;
char *city;
char *temp=NULL;
ch=getche();
while (ch!='\r')
{
if (i==0)
{
city=(char *)malloc(2*sizeof(char));
if (city==NULL)
{
printf("Memory Error!");
return 0;
}
city[0]=ch;
city[1]='\0';
}
else
{
free(temp);
temp=city;
city=(char *)malloc((i+2)*sizeof(char));
if (city==NULL)
{
printf("Memory Error!");
}
strcpy(city,temp);
city=ch;
city[i+1]='\0';
}
ch=getche();
i++;
}
return city;
}
/*
函数入口:字符串数组的首地址
函数输出:无返回值
函数功能:对城市名字进行排序
*/
void SortCity(char *city[])
{
int i,j;
char *temp;
for (i=1;i<N;i++)
{
for (j=0;j<N-i;j++)
{
if (strcmp(city[j],city[j+1])>0)
{
temp=city[j+1];
city[j+1]=city[j];
city[j]=temp;
}
}
}
}
Tags:  内存分配访问无效 内存分配 动态分配内存原理 c动态内存分配

延伸阅读

最新评论

发表评论