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
廣告