2D数组变量指针混乱 [英] 2D array variable pointer confusion

查看:58
本文介绍了2D数组变量指针混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对2D数组(C语言)有基本的疑问.考虑如下二维数组的声明

I have a basic doubt in 2D arrays (C Language). Consider a declaration of a 2D array as follows

int array[3][5];

现在,当我执行以下操作时,printf下方的两个输出都相同:

Now when I do the following, the output of both th below printf's is the same:

printf("%u\n", array);
printf("%u\n", *(array));

现在,当尝试执行以下操作时:

Now when try to to the following:

printf("%u\n", array+1);
printf("%u\n", *(array)+1);

输出是不同的.我得到第二个printf引用array [0] [1],第一个printf引用array [1] [0].这是如何运作的?数组是指向什么的指针?

The outputs are different. I get that the 2nd printf refers to array[0][1] and the first one to array[1][0]. How does this work? array is a pointer to what?

预先感谢

推荐答案

数组不是指针.忽略任何试图告诉您的答案,书籍或教程.

Arrays are not pointers. Ignore any answer, book, or tutorial that tries to tell you otherwise.

在大多数情况下,数组类型的表达式在编译时会被转换(转换为指向数组第一个元素的指针).例外是:

An expression of array type, in most contexts, is converted (at compile time) into a pointer to the array's first element. The exceptions are:

  • sizeof的操作数(sizeof arr产生数组的大小,而不是指针的大小)
  • 一元&的操作数(&arr产生数组的地址,而不是其第一个元素的地址-相同的内存位置,不同的类型).这与您的示例特别相关.
  • 用于初始化数组对象的初始化程序中的字符串文字(char s[6] = "hello";不复制字符串文字的地址,而是复制其值)
  • The operand of sizeof (sizeof arr yields the size of the array, not the size of a pointer)
  • The operand of unary & (&arr yields the address of the array, not of its first element -- same memory location, different type). This is particularly relevant to your example.
  • A string literal in an initializer used to initialize an array object (char s[6] = "hello"; doesn't copy the address of the string literal, it copies its value)

二维数组无非就是数组的数组.还有其他数据结构可以使用相同的x[y][z]语法使用,但它们不是真正的二维数组.是你的.

A 2-dimensional array is nothing more or less than an array of arrays. There are other data structures that can be used with the same x[y][z] syntax, but they're not true 2-dimensional arrays. Yours is.

[]索引运算符是根据指针算术定义的. x[y]表示*(x+y).

The [] indexing operator is defined in terms of pointer arithmetic. x[y] means *(x+y).

您的代码的行为遵循这些规则.

The behavior of your code follows from these rules.

阅读 comp.lang.c常见问题解答的第6节.这是我所见过的东西的最好解释.

Read section 6 of the comp.lang.c FAQ. It's the best explanation of this stuff I've seen.

也不要使用"%u"打印指针值;转换为void*并使用"%p".

And don't use "%u" to print pointer values; convert to void* and use "%p".

printf("%p\n", (void*)array);
printf("%p\n", (void*)*(array));

这篇关于2D数组变量指针混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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