zoukankan      html  css  js  c++  java
  • 内存分配调用

    通过函数给实参分配内存,可以通过二级指针实现

    #include<stdio.h>
    #incldue<stdlib.h>
    
    void getheap(int *p) //错误的模型
    {
        p = malloc(100);
    }
    
    void getheap(int **p) //正确的模型
    {
        *p = malloc(100);
    }
    int main()
    {
        int *p =NULL;
        getheap(&p);
        free(p);
        return 0;
    }

    如果出现以下错误:

    test.c:6:7: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]

      *p = malloc(100);

    是因为没有加上#include<stdio.h>的头文件。

    以下的方法也是可以的

    int *getheap() //正确的方法
    {
        return malloc(100);
    }
    
    int main()
    {
        int *p =NULL;
        p = getheap();
        free(p);
        return 0;
    }

    下面的写法是错误的:

    char *getstring() //错误的写法 
    {
        char array[10] = “hello”;
        return array;
    }
    int main()
    {
        char *s = getstring();
        printf(“s = %s
    ”,s);
        return 0;
    }

    原因是:

    char array[10] = “hello”;  //栈变量,在函数调用结束之后便被释放掉了

    下面方法返回结果可行:

    #include<stdio.h>
    
    char *getstring()
    {
        char *p = NULL;
        p = "string";
        return p;
    }
    
    int main()
    {
        char *p = NULL;
        p = getstring();
        printf("p = %s
    ",p);
        return 0;
    }

    不涉及到内存分配:

    char getstring()  //正确的写法
    {
        char c = ‘a’;
        return c;
    }    
    int main()
    {
        char c= getstring();
        printf(“c = %c
    ”,c);
        return 0;
    }

    是正确的。

    下面的写法也是可以的

    const char *getstring() //正确的
    {
        return “hello”;
    }
    int main()
    {
        const char *ss = getstring();
        printf(“ss = %s
    ”,ss);
        return 0;
    }

    常量在静态区,一直有效,直接返回地址是允许的。

    可以将常量的地址返回值返回

    或者:

    char *getstring() //函数可以正确返回
    {
        static char array[10] = “hello”; //在静态区域
        return array;
    }
    int main()
    {
        char *s = getstring();
    }
  • 相关阅读:
    SpringCloudStream实例
    Gateway环境搭建,通过YML文件配置
    Hystrix图形化监控
    Hystrix服务降级
    SpringBootのRedis
    springboot之缓存
    springboot整合JPA
    留言板
    Python 京东口罩监控+抢购
    2019年 自我总结
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11171772.html
Copyright © 2011-2022 走看看