zoukankan      html  css  js  c++  java
  • 函数和指针的运用

    #include <stdlib.h>
    
    int *f1(void)
    {
       int x = 10;
       return &x;
    }
    
    int *f2(void)
    {
       int *ptr;
       *ptr = 10;
       return ptr;
    }
    
    int *f3(void)
    {
       int *ptr;
       ptr = malloc(sizeof *ptr);
       return ptr;
    }
    
    f1和f2运用时有错误的。

    Function f1 returns the address of a local variable.  Since the variable’s lifetime ends after the function returns, any use of the return value produces undefined behavior.

    Function f2 produces undefined behavior because it dereferences and returns an uninitialized pointer.  (It has not been assigned to point to anything, and its initial value is indeterminate.)

    Function f3 has no errors (although its caller should make sure the return value is not NULL before using it, and call free when the memory is no longer needed).

    这里考的是返回一个指针的问题,一般来说返回指针的函数,里面一定有malloc之类的内存申请操作,传入指针类型,则是对指针指向的内容做修改。如果想修改指针本身,那就要传入指针的指针。
  • 相关阅读:
    洛谷P3799 妖梦拼木棒
    bzoj1008 [HNOI2008]越狱
    洛谷P3414 SAC#1
    洛谷P1078 文化之旅
    bzoj1053 [HAOI2007]反素数ant
    洛谷P1588 丢失的牛
    bzoj1085 [SCOI2005]骑士精神
    noip2016 蚯蚓
    noip2016 换教室
    html笔记03:表单
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007640.html
Copyright © 2011-2022 走看看