动态内存的使用
上一节的方法虽然可以避免溢出的问题,但会导致数据的丢失,下面我们就来学习一种更好的方法-动态内存的使用。由于动态内存是完全由用户自行分配使用的,因此需要用到一些系统调用,下面我们就分别学习它们。
首先我们需要的是动态内存分配的系统调用calloc()函数,其函数原型为:
#include void *malloc(size_t size); void *calloc(size_t nmemb,size_t size); |
#include void free(void *ptr); |
#include #include char *upcase(char *inputstring); int main(void) { char *str1; str1=upcase(“Everybody”); /*调用子函数upcase()*/ printf(“str1=%s \n”,str1); free(str1);/*释放内存*/ return 0; } char *upcase(char *inputstring) { char *newstring; int counter,N; N=strlen(inputstring); /*N为字符串长度*/ /*申请N+1个字节的内存空间,若出错则报错并退出*/ if(!(newstring=malloc(N+1))) { printf(“ERROR ALLOCATING MEMORY!\n”); exit(255); } /*将原字符串拷贝到新申请的内存块*/ strcpy(newstring,inputstring); for(counter=0;counter { if(newstring[counter]>=97&&newstring[counter]<=122) newstring[counter]-=32; /*将小写字母转换为大写字母*/ } return newstring; } |
EVERYBODY |
注意:在此程序的子函数中之所以可以使用N=strlen(inputstring),是因为此时inputstring是一个确定的字符串。而上一节中的4.1程序,newstring是一个未初始化的字符数组,故不能用strlen来求其长度。
(责任编辑:凌云通)
最新相关文章
发表评论