zoukankan      html  css  js  c++  java
  • 传参问题

    #include <stdio.h>

    #include <stdlib.h>

    void getmemory(char *p) //函数的参数是局部变量,在这里给它分配内存还在,但是P释放了。

    {

    p=(char *) malloc(100);

    }

    int main( )

    {

    char *str=NULL;

    getmemory(str);

    strcpy(str,"hello world");

    printf("%s/n",str);

    free(str);

    return 0;

    }

    答: 程序崩溃,getmemory中的malloc 不能返回动态内存, free()对str操作很危险

    修改后的程序如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    //引用
    /*void getmemory(char *&p)
    {
    p=(char *) malloc(100);

    }
    int main( )
    {
    char *str=NULL;
    getmemory(str);
    strcpy(str,"hello world");
    printf("%s ",str);
    free(str);
    return 0;
    }
    */

    //传地址的地址
    /*
    void getmemory(char **p)
    {
    *p=(char *) malloc(100);

    }
    int main( )
    {
    char *str=NULL;
    getmemory(&str);
    strcpy(str,"hello world");
    printf("%s ",str);
    free(str);
    return 0;
    }
    */

    char * getmemory()
    {
    //char*p=(char *) malloc(100);
     static char p[100];
     return p;

    }
    int main( )
    {
    char *str=NULL;
    str=getmemory();
    strcpy(str,"hello world");
    printf("%s ",str);
    //free(str);
    return 0;
    }


     运行结果如下:

  • 相关阅读:
    view和activity的区别
    接口对象的实例化在接口回调中的使用
    GreenDao
    HAOI 2012 高速公路
    SDOI2010 地精部落
    hdu 1505 City Game
    uva 1506 Largest Rectangle in a Histogram
    2017 济南综合班 Day 2
    uva 12325 Zombie's Treasure Chest
    uva 11212 Editing a Book
  • 原文地址:https://www.cnblogs.com/wangliangliang/p/3192326.html
Copyright © 2011-2022 走看看