Just My Life & My Work

最近要整合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?

廣告

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: