请解释d [2] [3]的值

时间:2016-04-24 08:07:00

标签: c pointers

第二行中分配给(* d)[4]的内容是什么?

来源:

#include<stdio.h>

int main()
{
    int c[20] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19},
        (*d)[4] = (int (*)[4])(c+5);

    printf ("d[2][3]: %d\n", d[2][3]);

    return 0;
}

输出:

  

d [2] [3]:16

2 个答案:

答案 0 :(得分:-1)

int (*d)[4] 

是一个指向整数的指针的数组。

假设整数占用系统中的4个字节,内存分配从零开始,即&c[0]zero

(*d)[4] = (int (*)[4])(c+5)

将使(* d)[0]具有值

c+5*sizeof(int)

0+5*4 = 20.

由于您正在进行转换,即(int*)20被视为内存地址,其值为整数,在您的情况下为5

详细说明:

d[0] will have the value 20 

&安培;

(*d)[0] will have the value 5 ie dereferencing the contents of address 20

当您执行[20]

时,内存被分配为一个连续的块

add - value
0   - 0
4   - 1
8   - 2
.
.
.
24 -  6
.
.
and so on

通过(*d)[4]我猜你试图把这个内存分成4 * 4块。 前4个(计数0到3)表示行(由计算由此决定为4),第二个4(计为0到3)表示您明确给出的列价值。

由于指针支持数组操作,

(* d)确实是*(d + 0),实际上是d [0]。你可以拥有最多

d[0][0],d[0][1],d[0][3],d[0][3]
.
.
.

d[3][0],d[3][1],d[3][2]

在您的情况下,值被分配到d[3][2](即19),并且没有为d [3] [3]分配值。如果你试图访问它,你可能会得到一个模糊的价值甚至程序崩溃。

答案 1 :(得分:-1)

指针算术非常可爱: - )

#include <stdio.h>

int main(void)
{
    // create a 1D array with size 20 containing the elements 0 to 19
    int c[20] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};

    // (c+5): c is a pointer to the first element of your array, hence c+5 points to the 5th element
    printf("c+5: %d\n", *(c+5)); // => 5

    // by casting (c+5) to (int (*)[4]), d is a pointer to a 2D-array with 4 columns and 4 rows
    // 2d-arrays are major row, hence the 4 from (int (*)[4]) indicates the number of columns
    int (*d)[4] = (int (*)[4])(c+5);

    // the array represented by d looks as follows
    //  5  6  7  8
    //  9 10 11 12
    // 13 14 15 16
    // 17 18 19 ?
    // As we do not have enough elements to fill the last row, we may not access the ? element

    // if we now select position [2][3], we select the value of the cell at row 2 and column 3 
    printf ("d[2][3]: %d\n", d[2][3]); // => 16

    return (0);
}