简体   繁体   English

C 中具有多维 arrays 的指针

[英]Pointers with multi dimensional arrays in C

int array[2][3] = {{2,3,6},{4,5,8}};

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

What will be the output of this and please explain how?这个 output 是什么,请解释一下如何?

Regards,问候,

Winston温斯顿

This call of printf printf 这个调用

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

invokes undefined behavior because there is used incorrect conversion specifier %d with a pointer expression.调用未定义的行为,因为在指针表达式中使用了不正确的转换说明符%d

If you will write instead如果你改写

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

then there will be outputted the address of the extent of memory occupied by the array that is the address of the first element of the array.则输出数组所占用的memory的extent的地址,即数组第一个元素的地址。

That is the expression *array has the type int'[3] .那就是表达式*array的类型为int'[3] Used as an argument in the call of printf it is implicitly converted to pointer to the first element of the type int * .printf的调用中用作参数,它被隐式转换为指向int *类型的第一个元素的指针。 It is the same as to write和写是一样的

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

Educate yourself on multidimensional arrays.自学多维 arrays。

Array array is a 2D array: Array array是一个二维数组:

int array[2][3] = {{2,3,6},{4,5,8}};

*array is the first element of array array because *array是数组array的第一个元素,因为

*array -> * (array + 0) -> array[0]

The first element of array array is array[0] , which is {2,3,6} . array array的第一个元素是array[0] ,即{2,3,6} The type of array[0] is int [3] . array[0]的类型是int [3] When you access an array, it is converted to a pointer to first element (there are few exceptions to this rule).当你访问一个数组时,它被转换为一个指向第一个元素的指针(这个规则很少有例外)。

So, in this statement所以,在这个声明中

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

*array will be converted to type int * . *array将被转换为int *类型。 The format specifier %d expect the argument of type int but you are passing argument of type int * .格式说明符%d需要int类型的参数,但您传递的是int *类型的参数。 The compiler must be throwing warning message for this.编译器必须为此抛出警告消息。 Moreover, wrong format specifier lead to undefined behaviour.此外,错误的格式说明符会导致未定义的行为。

If you want to print a pointer, use %p format specifier.如果要打印指针,请使用%p格式说明符。 Remember, format specifier %p expect that the argument shall be a pointer to void , so you should type cast pointer argument to void * .请记住,格式说明符%p期望参数是指向void的指针,因此您应该将强制类型转换指针参数键入void *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM