【问题标题】:Addresses in 2D Matrix二维矩阵中的地址
【发布时间】:2011-12-24 10:12:30
【问题描述】:

我想知道matrix&matrixmatrix[0]&matrix[0]+1有什么区别? nd 也是它的内存表示。

 int main(){
       int matrix[4][3];
       printf("%u\n",&matrix);
       printf("%u\n",&matrix+1);
       printf(" %u\n",matrix);
       printf("%u\n",matrix[0]+1);    
       printf(" %u\n",&matrix[0]);
       printf(" %u\n",&matrix[0]+1);
}

平台 ---- GCC ubuntu 10.04

【问题讨论】:

  • 你已经回答了你自己的问题。

标签: c matrix memory-address


【解决方案1】:

在 C 中,多维数组只是一个连续的内存块。在您的情况下,4 x 3 数组是 12 个元素的连续块,“矩阵”是指向内存块起始地址的指针。这里的matrix、matrix[0]、matrix[0][0]都是指内存块的起始地址

编译器将您的语句转换为

&matrix = get the starting address of the memory block
&matrix+1 = add '1' to matrix datatype, i.e. add 12 (total elements in matrix) * size of int (4 bytes) = 48 bytes.

matrix[0]+1 = address of first row, second element, i.e. &matrix[0][1]
&matrix[0] = address of first row, first element which is nothing but starting address of matrix
&matrix[0]+1 = add one row to starting address of matrix, i.e. 3 elements in a column * size of int(4 byte) = 12 bytes. Note that this is equivalent to (&matrix[0])+1 and not &(matrix[0]+1)

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2010-12-30
    • 2013-10-30
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多