创建void *的数组,每个都指向到2d INT矩阵? [英] Create an Array of void*, Each Pointing to 2d int Matrix?

查看:141
本文介绍了创建void *的数组,每个都指向到2d INT矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建无效* s的动态数组,每个无效* 将指向到2d INT 矩阵。

I want to create a dynamic array of void*s, each void* will point to 2d int matrix.

所有矩阵具有相同数量的行和列。

All of the matrices have the same number of rows and columns.

如何做到这在C?

我该怎么做我初始化后:无效** myArray的= NULL;

What do I do after I initialize: void **myArray = NULL;

更具体地说,我想创建一个功能,即需要2个参数:

More specifically, I want to create a function, that takes 2 parameters:

int foo( void* matrix, void** ptrArray)

其中,矩阵点到2d INT 矩阵, ptrArray 无效* s和返回的大小 ptrArray <数组/ code>。

Where matrix points to 2d int matrix, ptrArray points to an array of void*s, and foo returns the size of ptrArray.

我想,来获得2D INT 字模,并在它的一些操作,如在其切换一些数字。对于每一个变化,我做的,我想分配一个新的矩阵,并保存一个指向它 ptrArray

I want, foo to get the 2d int matrix from matrix and make some manipulations on it, like switch some numbers in it. For every change that I make, I want to allocate a new matrix, and save a pointer to it in ptrArray.

推荐答案

您必须动态地分配每个矩阵。

You'll have to dynamically allocate each matrix.

有关示例的目的,我将假定你正在创建你的2D INT 矩阵作为一个线性,16 INT 阵列。

For purposes of example I'm going to assume that you are creating your "2d int matrix" as a linear, 16 int array.

#define MATRIX_SIZE 16

int foo(void* matrix, void** ptrArray){
    assert(ptrArray == NULL);

    int result = 0;
    int* first = malloc(MATRIX_SIZE * sizeof(int));

    //do stuff to matrix
    for(int i = 0; i < MATRIX_SIZE; ++i){
        first[i] = matrix[i];
    }
    ptrArray = malloc((++result) * sizeof(void*));
    ptrArray[0] = (void*)first;

    int* second = malloc(MATRIX_SIZE * sizeof(int));

    //do stuff to matrix
    for(int i = 0; i < MATRIX_SIZE; ++i){
        second[i] = matrix[i];
    }
    ptrArray = realloc((++result) * sizeof(void*));
    ptrArray[1] = (void*)second;
    .
    .
    .
    return result;
}

这篇关于创建void *的数组,每个都指向到2d INT矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆