如何从C中的函数返回指针?

本文概述

在C语言中,指针是一个用来存储另一个变量的内存地址的变量。我们可以将指针传递给函数,也可以将指针从函数返回。但不建议在函数返回后返回局部变量的地址,因为它超出了函数的作用域。

程序1:

下面的程序将给出细分错误, 因为’一种’对于该函数而言是本地的:

C

//C program to illustrate the concept of
//returning pointer from a function
#include <stdio.h>
  
//Function returning pointer
int * fun()
{
     int A = 10;
     return (&A);
}
  
//Driver Code
int main()
{
     //Declare a pointer
     int * p;
  
     //Function call
     p = fun();
  
     printf ( "%p\n" , p);
     printf ( "%d\n" , *p);
     return 0;
}

输出如下:

以下是上述程序的输出:

如何从C中的函数返回指针1

说明:

这种情况下的主要原因是, 编译器总是使叠用于函数调用。一旦函数退出函数栈得到删除导致函数的局部变量超出范围。

静态变量即使它们超出范围也具有保留其价值的特性。因此, 要执行从C中的函数返回指针的概念, 必须将局部变量定义为静态变量。

程序2:

C

//C program to illustrate the concept of
//returning pointer from a function
#include <stdio.h>
  
//Function that returns pointer
int * fun()
{
     //Declare a static integer
     static int A = 10;
     return (&A);
}
  
//Driver Code
int main()
{
     //Declare a pointer
     int * p;
  
     //Function call
     p = fun();
  
     //Print Address
     printf ( "%p\n" , p);
  
     //Print value at the above address
     printf ( "%d\n" , *p);
     return 0;
}

输出如下:

0x601038
10

来源:

https://www.srcmini02.com/68736.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_39766.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?