zoukankan      html  css  js  c++  java
  • (1) 编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间。new(n)表示分配n个字节的内存空间。(2)写一函数free,将前面用new函数占用的空间释放。free(p)表示将p(地址)指向的单元以后的内存段释放。

    (1) 编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间。new(n)表示分配n个字节的内存空间。(2)写一函数free,将前面用new函数占用的空间释放。free(p)表示将p(地址)指向的单元以后的内存段释放。

    解题思路: 封装malloc函数申请空间,封装free函数释放空间;

    答案:

    #include <stdio.h>
    #include <stdlib.h>
    
    void *mynew(int n)
    {
    	return malloc(n);
    }
    void myfree(char *p)
    {
    	return free(p);
    }
    int main()
    {
    	int num;
    	char *str = NULL;
    	printf("Please enter number: ");
    	scanf_s("%d", &num);
    	printf("before new p--%p:%s
    ", str, str);//申请空间之前,查看指针的地址和指向空间数据
    	str = (char*)mynew(num);
    	printf("after new p--%p:%s
    ", str, str);//申请空间之后,查看指针的地址和指向空间数据
    	printf("Please enter a string:");
    	scanf_s("%s", str, num);
    	printf("before free p--%p:%s
    ", str, str);//释放空间之前,查看指针的地址和指向空间数据
    	myfree(str);
    	printf("after free p--%p:%s
    ", str, str);//释放空间之后,查看指针的地址和指向空间数据
    	system("pause");
    	return 0;
    }
    

     (1) 编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间。new(n)表示分配n个字节的内存空间。(2)写一函数free,将前面用new函数占用的空间释放。free(p)表示将p(地址)指向的单元以后的内存段释放。

  • 相关阅读:
    mybatis-generator自动生成dao,mapping,model
    cent os 6.5+ambari+HDP集群安装
    cent os 6.5 配置vsftpd
    Ambari修改主页面方法
    Maven .m2 epositoryjdk ools1.7 missing
    Chrome封掉不在chrome商店中的插件解决办法
    Hadoop 读取文件API报错
    Hadoop创建/删除文件夹出错
    mysql性能测试(索引)
    Greys--JVM异常诊断工具
  • 原文地址:https://www.cnblogs.com/weiyidedaan/p/13292962.html
Copyright © 2011-2022 走看看