gpt4 book ai didi

c - 多维数组,不同方式表示grid[22][0]的地址

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:22 24 4
gpt4 key购买 nike

我目前正在研究c语言的多维数组和指针。

我被问到以下问题

Suppose you have the following declaration:

int grid[30][100];.

Express the address of grid[22][0] two ways.

作者提供了以下答案

&grid[22][0] or grid[22]

我想到了

//notice for the second answer, I placed an address operator & at the front 
&grid[22][0] or &grid[22]

我用下面的代码进行了测试

#include <stdio.h>

int main(void){

int ar[2][3] = {
{11, 22, 33},
{44, 55, 66}
};

printf("%p\n", &ar[2][0]);
printf("%p\n", ar[2]);
printf("%p\n", &ar[2]);

return 0;
}

并且所有三种形式打印相同的值

0062ff30
0062ff30
0062ff30

那么作者的回答grid[22]和我的回答&grid[22]是等价的吗?怎么可能等价呢?

最佳答案

首先,如果你使用%p,那么你必须将值转换为(void*),因为 %p 期望 a 期望一个空指针

printf("%p\n", (void*) &ar[2][0]);
printf("%p\n", (void*) ar[2]);
printf("%p\n", (void*) &ar[2]);

他们都有相同的地址(因为他们都在同一个地方内存),但它们的表达式属于不同类型:

&ar[2][0];

是一个int*(指向int的指针)

ar[2];

是一个int[3](维度3的int数组),但是在printf中它衰减为一个 int*,然后由于转换而变成一个 void*

&ar[2];

int (*)[3](指向 int[3] 的指针,int 维度 2 的数组)。

当你使用 sizeof 时你可以看到 int[3] 是一个数组 which arrays do不衰减为指针:

printf("sizeof &ar[2][0]: %zu\n", sizeof &ar[2][0]);
printf("sizeof ar[2]: %zu\n", sizeof ar[2]);
printf("sizeof &ar[2]: %zu\n", sizeof &ar[2]);

这会打印(在我的系统上,x86_64):

sizeof &ar[2][0]: 8         (size of an pointer)
sizeof ar[2]: 12 (size of an array `int[3]`)
sizeof &ar[2]: 8 (size of a pointer)

如果你有这个功能

void foo(int *x)
{
(void) x; // to silence -Wall warnings
}

然后 foo(&ar[2][0]) 很好并且 foo(ar[2]) 也很好,因为它会衰减成一个指针。但是 foo(&ar[2]) 不行,你会得到:

a.c: In function ‘main’:
a.c:21:6: warning: passing argument 1 of ‘foo’ from incompatible pointer type [-Wincompatible-pointer-types]
foo(&ar[2]);
^
a.c:3:6: note: expected ‘int *’ but argument is of type ‘int (*)[3]’
void foo(int *x)
^~~

但是对于

void bar(int (*x)[3])
{
(void) x;
}

bar(&ar[2]) 没问题。

请记住,如果您使用任何方式打印值/访问内存这些表达式,您将越界访问数据。 ar 应该是

int ar[3][3] = {
{11, 22, 33},
{44, 55, 66},
{77, 88, 99}
};

关于c - 多维数组,不同方式表示grid[22][0]的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49142137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com