zoukankan      html  css  js  c++  java
  • 指针的高阶用法——从函数返回指针

    在上一章中,我们已经了解了 C 语言中如何从函数返回数组,类似地,C 允许您从函数返回指针。为了做到这点,您必须声明一个返回指针的函数,如下所示:

    int * myFunction()
    {
    .
    .
    .
    }
    

    另外,C 语言不支持在调用函数时返回局部变量的地址,除非定义局部变量为 static 变量。

    现在,让我们来看下面的函数,它会生成 10 个随机数,并使用表示指针的数组名(即第一个数组元素的地址)来返回它们,具体如下:

    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h> 
    
    /* 要生成和返回随机数的函数 */
    int * getRandom( )
    {
       static int  r[10];
       int i;
     
       /* 设置种子 */
       srand( (unsigned)time( NULL ) );
       for ( i = 0; i < 10; ++i)
       {
          r[i] = rand();
          printf("%d
    ", r[i] );
       }
     
       return r;
    }
     
    /* 要调用上面定义函数的主函数 */
    int main ()
    {
       /* 一个指向整数的指针 */
       int *p;
       int i;
     
       p = getRandom();
       for ( i = 0; i < 10; i++ )
       {
           printf("*(p + [%d]) : %d
    ", i, *(p + i) );
       }
     
       return 0;
    }
    

    当上面的代码被编译和执行时,它会产生下列结果:

    1523198053
    1187214107
    1108300978
    430494959
    1421301276
    930971084
    123250484
    106932140
    1604461820
    149169022
    *(p + [0]) : 1523198053
    *(p + [1]) : 1187214107
    *(p + [2]) : 1108300978
    *(p + [3]) : 430494959
    *(p + [4]) : 1421301276
    *(p + [5]) : 930971084
    *(p + [6]) : 123250484
    *(p + [7]) : 106932140
    *(p + [8]) : 1604461820
    *(p + [9]) : 149169022
  • 相关阅读:
    什么是浮动IP
    How can I detect multiple logins into a Django web application from different locations?
    git add -A使用说明
    理解水平扩展和垂直扩展
    php != 和 !== 的区别
    wireshark:Couldn't run /usr/bin/dumpcap in child process: Permission denied
    Unable to VNC onto Centos server remotely
    systemctl使用说明
    KiB、MiB与KB、MB的区别
    python带setup.py的包的安装
  • 原文地址:https://www.cnblogs.com/JingWenxing/p/10263849.html
Copyright © 2011-2022 走看看