zoukankan      html  css  js  c++  java
  • c++ primer 函数传值1

    不看c++ primer  永远不知道自己基础有多差


    函数的參数传值一般有两种方式:值传递,引用传递。


    值传递有以下两种形式:

    void func( int a )
    {
    //
    }
    
    void func1( int *a )
    {
    //
    }

    对于 func 和func1都是通过拷贝内存来实现的

    func1

    int m = 10 ;
    func1( int *a ) ;
    //处理过程为: a = &m ;  
    //然后通过指针 *a 对 m进行间接操作

    传引用

    void func2( int &a )
    {
    //
    }
    引用就是变量的一个别名,不会发生内存的拷贝



    典型的面试题:

    void GetMemory1(char *p)
    {
        p = (char *)malloc(100);
    }
    
    void Test1(void) 
    {
        char *str = NULL;
        GetMemory1(str); 
        strcpy(str, "hello world");
        printf(str);
    }
    <p>
    </p><pre name="code" class="cpp">// p = str;
    // p = malloc(...);
    //p和str有半毛线关系?

    char *GetMemory2(void)
    { 
    	char p[] = "hello world";
    	return p;
    }
    void Test2(void)
    { 
    	char *str = NULL; 
    	str = GetMemory2(); 
    	printf(str);
    
    }
    char *GetMemory3(void)
    { 
    	return 
    		"hello world";
    }
    void Test3(void)
    { 
    	char *str = NULL; 
    	str = GetMemory3(); 
    	printf(str);}
    //Test3 中打印hello world,由于返回常量区,并且并没有被改动过。Test2中不一定能打印出hello world,由于指向的是栈。
    void GetMemory4(char **p, int num)
    { 
    	*p = (char *)malloc(num);
    
    }
    void Test4(void)
    { 
    	char *str = NULL; 
    	GetMemory3(&str, 100); 
    	strcpy(str, "hello"); 
    	printf(str); 
    }//内存没释放
    void Test5(void)
    { 
    	char *str = (char *) malloc(100); 
    	strcpy(str, "hello"); 
    	free(str); 
    	if(str != NULL) 
    	{ 
    		strcpy(str, "world"); 
    		printf(str); 
    	}
    }//str为野指针,打印的结果不得而知
    void Test6()
    { 
    	char *str=(char *)malloc(100); 
    	strcpy(str, "hello"); 
    	str+=6; 
    	free(str); 
    	if(str!=NULL) 
    	{ 
    		strcpy(str, "world"); printf(str); 
    	}
    }//VC断言失败,执行错误











  • 相关阅读:
    APP 弱网测试可能会出现的bug
    Monkey 稳定性测试
    设计模式 策略模式
    设计模式 单例模式
    Linux常用命令(三)文件权限管理
    Linux常用命令(二)文件目录管理命令
    Linux常用命令(一)
    WSL安装yum报错:E: Unable to locate package yum
    使用LxRunOffline迁移WSL
    关于PyQt5 setPalette 设置背景不生效问题
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4004355.html
Copyright © 2011-2022 走看看