C语言函数中返回指针



C语言编程中,一个函数可以定义为有多个参数,但它只能向调用函数返回一个表达式。

一个函数可以返回单个值,该值可以是任何类型的变量,例如基本类型(如int、float、char等)、指向基本类型或用户定义类型变量的指针,或者指向任何变量的指针。

阅读本章,了解C程序中函数返回指针的不同方法。

从C语言函数中返回静态数组

如果函数具有局部变量或局部数组,则返回局部变量的指针是不可接受的,因为它指向一个不再存在的变量。请注意,局部变量一旦函数作用域结束就将不复存在。

示例1

下面的示例演示了如何在被调用函数(arrfunction)内使用静态数组并将它的指针返回给main()函数

#include <stdio.h>
#include <math.h>

float * arrfunction(int);

int main(){

   int x = 100, i;
   float *arr = arrfunction(x);

   printf("Square of %d: %f\n", x, *arr);
   printf("Cube of %d: %f\n", x, arr[1]);
   printf("Square root of %d: %f\n", x, arr[2]);

   return 0;
}

float *arrfunction(int x){
   static float arr[3];
   arr[0] = pow(x,2);
   arr[1] = pow(x, 3);
   arr[2] = pow(x, 0.5);

   return arr;
}

输出

运行此代码时,将产生以下输出:

Square of 100: 10000.000000
Cube of 100: 1000000.000000
Square root of 100: 10.000000

示例2

现在考虑以下函数,它将生成10个随机数。它们存储在一个静态数组中,并将它们的指针返回给main()函数。然后,在main()函数中遍历该数组,如下所示:

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

/* function to generate and return random numbers */
int *getRandom() {
   static int  r[10];
   srand((unsigned)time(NULL));    /* set the seed */
  
   for(int i = 0; i < 10; ++i){
      r[i] = rand();
   }
    
   return r;
}

int main(){

   int *p;     /* a pointer to an int */
   p = getRandom();

   for(int i = 0; i < 10; i++) {
      printf("*(p + %d): %d\n", i, *(p + i));
   }

   return 0;
}

输出

运行代码并检查其输出:

*(p + 0): 776161014
*(p + 1): 80783871
*(p + 2): 135562290
*(p + 3): 697080154
*(p + 4): 2064569097
*(p + 5): 1933176747
*(p + 6): 653917193
*(p + 7): 2142653666
*(p + 8): 1257588074
*(p + 9): 1257936184

从C语言函数中返回字符串

使用相同的方法,您可以将字符串传递给函数并从函数返回字符串。C语言中的字符串是char类型的数组。在下面的示例中,我们使用指针传递字符串,在函数中操作它,然后将其返回给main()函数。

示例

在被调用函数中,我们使用malloc()函数分配内存。传递的字符串在返回之前与局部字符串连接。

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

char *hellomsg(char *);

int main(){

   char *name = "TutorialsPoint";
   char *arr = hellomsg(name);
   printf("%s\n", arr);
   
   return 0;
}

char *hellomsg(char *x){
   char *arr = (char *)malloc(50*sizeof(char));
   strcpy(arr, "Hello ");
   strcat(arr, x);
   
   return arr;
}

输出

运行代码并检查其输出:

Hello TutorialsPoint

从C语言函数中返回结构体指针

下面的示例演示了如何返回struct类型变量的指针。

这里,area()函数有两个按值传递的参数。main()函数从用户读取长度和宽度,并将它们传递给area()函数,area()函数填充一个struct变量并将它的引用(指针)返回给main()函数。

示例

查看程序:

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

struct rectangle{
   float len, brd;
   double area;
};

struct rectangle * area(float x, float y);

int main(){

   struct rectangle *r;
   float x, y;
   x = 10.5, y = 20.5;
   r = area(x, y);

   printf("Length: %f \nBreadth: %f \nArea: %lf\n", r->len, r->brd, r->area);

   return 0;
}

struct rectangle * area(float x, float y){
   double area = (double)(x*y);
   static struct rectangle r;
   r.len = x; r.brd = y; r.area = area;
   
   return &r;
}

输出

运行此代码时,将产生以下输出:

Length: 10.500000 
Breadth: 20.500000 
Area: 215.250000
广告
© . All rights reserved.