最近要整合C/C++高人寫的Source Code,發現我自己好像斷手斷腳XD,因為要搞較為底層的記憶體空間配置⋯⋯先前寫Objective C多麼愜意,用不到的記憶體空間,系統會自動去釋放,但是在C/C++就要自己寫code處理呢!
現在想要配置2D陣列 (Allocate 2D Array),要怎麼做才好辦事呢?
以後都來這兒複製貼上吧XD~
/**
Theme: Allocate 2D Array
IDE: Xcode 9
Language: C
Date: 107/03/30
Author: HappyMan
Blog: https://cg2010studio.com/
*/
#include
#include
float** createArray(int m, int n)
{
float* values = calloc(m * n, sizeof(float));
float** rows = malloc(n * sizeof(float*));
for (int i = 0; i < n; ++i) {
rows[i] = values + i*m;
}
return rows;
}
void destroyArray(float** arr)
{
free(*arr);
free(arr);
}
int main()
{
float** happyArr = createArray(2,3);
happyArr[0][0] = 1;
happyArr[0][1] = 1;
happyArr[1][0] = 2;
happyArr[1][1] = 2;
happyArr[2][0] = 3;
happyArr[2][1] = 3;
destroyArray(happyArr);
return 0;
}
我發現顯示code的外掛會讓下面兩行出問題~
#include <stdio.h>
#include <stdlib.h>
最後記得釋放記憶體唷~
參考:How to return a 2D array to a function in C?。
HappyMan・迴響