如何使用指標從函式返回一個數組。
阿新 • • 發佈:2019-01-05
#include <iostream> #include <stdlib.h> using namespace std; //這裡function是一個函式,它返回一個指標,該指標指向的是包含20個int型別元素的陣列。 int (*function())[20] { int i=0; int (*p)[20];//宣告一個指向20個元素的指標; p=(int(*)[20])calloc(20,sizeof(int)); //或者p=(int (*)[20])malloc(sizeof(int)*20); if(!p)//記憶體不夠; { cout<<"the memory is not enough!"<<endl; return NULL; } for(i=0;i<20;i++) (*p)[i]=i+5; return p; } int main() { int (*result)[20]; result=function(); if(result) { cout<<result[7]<<endl;//這樣訪問結果,應該輸出8。 free(result); } system("pause"); return 0; }