[英]Why array holds the address of the first element in C?
Some says that array in c is not a pointer to the first element of the array why is array name a pointer to the first element of the array? 有人说c中的数组不是指向数组第一个元素的指针, 为什么数组名是指向数组第一个元素的指针? So when you print the array in c using "printf" for example why it is showing the address of the first element instead of the array elements? 因此,当您使用“printf”在c中打印数组时,为什么它显示第一个元素的地址而不是数组元素?
Update: 更新:
const char h[10]="Hello";
printf("%p", h);
Output: 00AFFE0C 输出:00AFFE0C
well as one answer said said that this happens because of the %type I specified and that made sense because when I write 正如一个答案所说,这是因为我指定的%类型,这是有道理的,因为我写的时候
printf("%s", h);
OR
printf(h);
Output: Hello 输出:你好
here two questions rises: 这里有两个问题:
1) In printf(h); 1)在printf(h)中; why it is not decaying the array and printing the pointer value because in decaying array will be converted to pointer 为什么它不会衰减数组并打印指针值,因为在衰减数组中将转换为指针
2) how can I print an array of int in the same way ie what is the %type in printf for array of int 2)如何以相同的方式打印int数组,即int数组的printf中的%类型
The difference between an array and a pointer is that the compiler knows about the array size and dimensions so it can perform some static checks address computations that are not possible with just pointers. 数组和指针之间的区别在于编译器知道数组的大小和大小,因此它可以执行一些静态检查,解决仅使用指针无法实现的计算。
Additionally in the case of printf() it doesn't matter what you pass it because it's a variadic function. 另外,在printf()的情况下,传递它并不重要,因为它是一个可变参数函数。 It doesn't know anything about the type of the arguments that you pass it except from the format string so if you pass a %s
argument you're in effect casting it to char*
. 除了格式字符串之外,它对你传递的参数类型一无所知,所以如果传递%s
参数,你实际上将它转换为char*
。 The only reason the compiler may give you a warning if you pass an argument of the wrong type is because it's an intrinsic function and the compiler knows about it. 如果传递错误类型的参数,编译器可能会给出警告的唯一原因是因为它是一个内部函数,编译器知道它。
Most functions that take arrays take them as pointer arguments so you're also implicitly casting the array to a pointer when calling a function unless the function specifies an array type as argument. 大多数采用数组的函数都将它们作为指针参数,因此除非函数指定数组类型作为参数,否则在调用函数时也会隐式地将数组转换为指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.