c语言 动态分配空间问题

有没有人在啊,想请分析下,c语言 动态分配空间问题?

要求是输入n,建立一个长度为n的动态指针数组,用于保存n个字符数组的内存地址。在读入每个字符串时,用一个长度为1000的字符数组做为缓冲数组,然后再动态分配空间,将缓冲数组中的字符串复制到新分配的动态空间中,并将动态空间的首地址保存到指针数组中。读完n个字符串后将这n个字符串按ASCLL码的顺序升序排序输出,帮忙改一下,多谢各位大神!!!!!!!!!!!!!!(很急,勿喷……计算机学渣妹子一枚)
#include<stdio.h>#include<stdlib.h>#define N 100int strCmp(char * s,char * t){ while(*s!='\0' && *t!='\0' && *s==*t){ s++; t++; } if(*s==*t) //若结束比较时s和t所指字符相等,则肯定都指向‘\0’ return 0; else if (*s>*t)//任何一个字符均大于‘\0’ return 1; else return -1; }main(){ int n,i,pass,m; char * *a,b[100][100],temp; printf("Please input the number of integers:"); scanf("%d",&n); printf("Please input the strings:\n"); for(i=0;i<n;i++) gets(b[i]); a = (char * *)malloc(sizeof(char *)*n); for(i=0;i<n;i++) a[i]=(char *)malloc(sizeof(char)*n); if ( a==NULL ) /*内存申请失败:提示,退出*/ printf("out of memory"); for(i=0;i<n;i++) a[i]=b[i]; for(pass=0;pass<=n-1;pass++) { for(i=0;i<=n-2;i++) { m=strCmp(a[i],a[i+1]); if(m==1) { temp=*a[i]; *a[i]=*a[i+1]; *a[i+1]=temp; } } } printf("The reuslt is:\n"); for(i=0;i<n;i++) { puts(a[i]); printf("\n"); } for(i=0;i<n;i++) free(a[i]); free(a); return 0; }
最新回答
鸿笺钟书

2025-03-29 08:37:47

我就不改了,给你重写得了,你研究好了应该就差不多了。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
   int n,i,j,length;
   char **p=NULL,**out=NULL,*tmpP;
   char tmp[1000]={0};
   scanf("%d",&n);
   getchar();   //清回车
   if((p=(char **)malloc(n*sizeof(char *)))==NULL)
   {
     printf("Out of memory!\n");
     exit(0);
   }
   if((out=(char **)malloc(n*sizeof(char *)))==NULL)
   {
     printf("Out of memory!\n");
     exit(0);
   }
   for(i=0;i<n;i++)
   {
      gets(tmp);
      length=strlen(tmp);
      if((p[i]=(char *)malloc(length+1))==NULL)
      {
         printf("Out of memory!\n");
         exit(0);
      }
      out[i]=p[i];
      memset(p[i],0,length+1);
      strncpy(p[i],tmp,length);
   }
   for(i=0;i<n-1;i++)
    for(j=i+1;j<n;j++)
    {
       if(strcmp(out[i],out[j])>0)
       {
         tmpP=out[i];
         out[i]=out[j];
         out[j]=tmpP;
       }
    }
   printf("Output:\n"); 
   for(i=0;i<n;i++)
   {
      puts(out[i]);
      free(out[i]);
      out[i]=NULL;
   } 
   free(out);
   free(p);
   out=NULL;
   p=NULL;  
}

你永久不要离开我~

2025-03-29 04:23:37

你是想对字符串排序么?

两个地方:

加个getchar,吸收掉输入int时输入的回车

    scanf("%d",&n);
    getchar();


交换指针,而不是交换第一个字符,temp定义成指针

char * *a,b[100][100],*temp;


            if(m==1)
            {
                temp=a[i];
                a[i]=a[i+1];
                a[i+1]=temp;
            }

这样就可以了。

代码写得不错,多调试