如何在不使用运算符[]的情况下在C中打印2D数组? [英] How to print a 2D-array in C, without using the operator []?

查看:76
本文介绍了如何在不使用运算符[]的情况下在C中打印2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用[]打印2D矩阵,我想像指针一样使用*.
因此,对于一维数组,我会这样做:例如*(arr+i). matrix[][]中用来替换的语法是什么?

I am trying to print a 2D matrix with using [], instead I want to use * like a pointer.
So with a 1 D array I'd do: *(arr+i) for example. What's the syntax used to replace in matrix[][] ?

代码如下:

for (i = 0; i < size; i++)
{
    for (j = 0; j < (size * 2); j++)
    {
        printf(" %5d", matrix[i][j]);
    }
    printf("\n");
}

P.S, 我确实尝试过以下几种方法:

P.S, I did try several things like:

*(matrix+i+j);
*(matrix+i)+*(matrix+j);

当然,这些都不起作用.

Of course none of that worked.

感谢您的帮助和时间!

推荐答案

这可能取决于matrix的分配或传递给函数的方式.

This may depend on how matrix was allocated or passed to a function.

int A[10][15];

这将使用连续的内存块.要在不使用数组表示法的情况下处理元素,请使用:

This uses a contiguous block of memory. To address the elements without using array notation use:

        A +(i*15)+j    // user694733 showed this is wrong
((int *)A)+(i*15)+j    // this is horribly ugly but is correct

请注意15,因为每行包含15个元素.此处的其他答案中提供了更好的解决方案.

Note the 15, as each row consists of 15 elements. Better solutions are presented in other answers here.

以下:

int *A[10];

A是10个指向int的指针的数组.假定已使用malloc分配了每个数组元素,则在不使用数组表示法的情况下即可对元素进行寻址:

A is an array of 10 pointers to ints. Assuming each array element has been allocated using malloc, you address the elements without using array notation as:

*(A+i) + j;

也就是说,您采用A,然后采用第i个元素,对该元素取消引用,并添加j作为第二个索引.

that is, you take A, then take the ith element, dereference that and add j as the second index.

-编辑-

并且要完整:

int foo(int *p)

此处,函数仅接收指向零个或多个整数的指针.指针指向一个连续的线性内存块,您可以在其中放置一个n维数组.函数只能通过参数或全局变量知道多少个维度以及每个维度的上限.

here a function just receives a pointer to zero or more ints. The pointer points to a contiguous, linear block of memory into which you can place an n-dimensional array. How many dimensions there are and the upper bound of each dimension the function can only know through parameters or global variables.

要寻址n维数组的单元格,程序员必须使用上述表示法自己计算地址.

To address the cells of the n-dimensional array, the programmer must calculate the addresses him/herself, using the above notation.

int foo3(int *m, int dim2, int dim3, int i,  int j, int k)
{
    int *cell = m + i*dim3*dim2 + j*dim2 + k;
    return *cell;
}

这篇关于如何在不使用运算符[]的情况下在C中打印2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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