1、malloc函数:向系统申请分配指定size个字节的内存空间,分配成功后得到的是一个内存块,即连续的空间 2、malloc分配不一定成功,所以最好验证一下: char *mallo; if ((mallo=(char *)malloc(36*sizeof(char)))==NULL) printf(“error in mallo!\n”); 3、传指针参数的原理在谭浩强书上已经讲过,这里只是做传指针后实际的赋值方式探讨 传递过来的参数:char *mallo 3.1:mallo=“bag”;/*直接=不成功,调用后mallo只能在这个函数中打印出,调用这个函数的函数却不能在调用后得到相应的赋值结果*/ 3.2:for(;i<36;i++) { *(mallo++)='a'+rand()%26; //mallo[i]='a'+rand()%26;/*这句和上句的效果相同*/ }/*for循环可以成功:依次赋值随进字母*/ 3.3:char *test=mallo; for(;i<36;i++) { *(test++)='a'+rand()%26; //test[i]='a'+rand()%26; }/*效果和3.2基本相同,只是让思路更清晰的一种做法*/ 3.4:strcpy(mallo,“bag”);/*strcpy可以成功:strcpy会把“bag”中的三个字符和‘\0’一个一个的拷贝到mallo中,和上面的for循环类似*/ 一开始在Linux下这种方式并没成功,在windows下添加#includes<string.h>后成功了(windows下没有这个include会报错),再回到Linux下也能赋值成功,估计可能是没有#includes<string.h>的缘故,但 奇怪的是,我再去掉#includes<string.h>,还是成功,原因便无从知晓了。 4、源码 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> /*接受传过来的指针,并通过几种方式赋值*/ void memtest(char *mallo) { int i=0; //char *test=mallo; printf(“===============================================================”); //printf(“\n*mallo:%s\n”,*mallo); printf(“\nmallo: %s\n”,mallo); /*for(;i<36;i++) { *(mallo++)='a'+rand()%26; mallo[i]='a'+rand()%26; }*//*for循环可以成功*/ strcpy(mallo,“bag”);/*strcpy可以成功*/ //mallo=“bag”;/*直接=不成功*/ //printf(“test:%s\n”,test); printf(“\n\”bug\“ ->mallo: %s\n”,mallo); } void main() { char *mallo; if ((mallo=(char *)malloc(36*sizeof(char)))==NULL)/*申请空间*/ printf(“error in mallo!\n”); //memset(mallo,1,sizeof(mallo)); //mallo=“shanghaimizhuan”; printf(“mallo_main: %s\n”,mallo);/*打印申请空间内容,在windows下为乱码,而Linux下不显示*/ /*以下打印数据在Linux和windows下数据不同,在赋值成功前windows已经会检测上面分配的空间大小,Linux则不会:strlen(mallo)可以看出*/ printf(“sizeof(mallo):%d--分割线--sizeof(*mallo):%d--分割线--strlen(mallo):%d\n”,sizeof(mallo),sizeof(*mallo),strlen(mallo)); memtest(mallo);/*调用赋值函数*/ printf(“===============================================================”); printf(“\nmallo_aftersetparam:%s\n”,mallo);/*调用后输出*/ printf(“sizeof(mallo):%d--分割线--sizeof(*mallo):%d--分割线--strlen(mallo):%d\n”,sizeof(mallo),sizeof(*mallo),strlen(mallo)); free(mallo); } |