这是返回一个二维阵列的有效方式是什么? [英] Is this a valid way to return a two-dimensional array?

查看:102
本文介绍了这是返回一个二维阵列的有效方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下 C - code:

 的#include<&stdio.h中GT;INT MAT1 [2] [4] = {
    {9,10,11,12},
    {13,14,15,16}
};INT(*(转)(中间体矩阵[] [4]))[2] {
    静态INT垫[4] [2];
    INT I;
    诠释J;    的printf(我的功能转()\\ n和我调换的2x4矩阵\\ n \\ n);
    对于(I = 0; I&2;我++){
        为(J = 0; J&下; 4; J ++){
            垫[J]。[I] =矩阵[I] [J]。
        }
    }
    返回垫;
}诠释主(){
    INT(* mat_transpose)[2];
    INT I;
    诠释J;
    mat_transpose =转(MAT1);    为(J = 0; J&2; J ++){
        对于(I = 0; I&下; 4;我++){
            的printf(mat_transpose [%D]。[%D]。=%d个\\ N,I,J,mat_transpose [I] [J]);
        }
    }
    返回0;
}

功能转()返回一个二维数组(或相当的指针,指针数组,我猜)。这是实现这一目标的有效途径?通过各种提问#1看,好像有这样做的没有标准的方式,而是一个伟大的多。是否有关于返回二维或多维数组的一些标准?


解决方案

  

这是返回一个二维数组一个有效的方法是什么?


是的。返回一个指针静态本地变量是有效的。有一件事,我建议是,你可以通过的typedef 的返回类型

 的typedef MATX [2];MATX *转(INT矩阵[] [4])){/ *函数体* /}

Given the following C-code:

#include <stdio.h>

int mat1[2][4] = {
    {9, 10, 11, 12},
    {13, 14, 15, 16}
};

int (*(transpose)(int matrix[][4]))[2] {
    static int mat[4][2];
    int i;
    int j;

    printf("I am the function transpose()\nand I'm transposing 2x4 matrices.\n\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 4; j++) {
            mat[j][i] = matrix[i][j];
        }
    }
    return mat;
}

int main() {
    int (*mat_transpose)[2];
    int i;
    int j;
    mat_transpose = transpose(mat1);

    for (j = 0; j < 2; j++) {
        for (i = 0; i < 4; i++) {
            printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
        }
    }
    return 0;
}

The function transpose() returns a two-dimensional array (Or rather a pointer to an array of pointers, I guess.). Is this a valid way to achieve this? Looking through various Stackoverflow questions it seems like there is no standard way of doing this but rather a great many. Is there some standard regarding returning two- or multi-dimensional arrays?

解决方案

Is this a valid way to return a two-dimensional array?

Yes. Returning a pointer to static local variable is valid. One thing I would suggest is that you can typedef that return type

typedef matx[2];  

matx *transpose(int matrix[][4])){ /* Function body */ }

这篇关于这是返回一个二维阵列的有效方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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