为什么我不能将数组分配直接在C指针? [英] Why can't I assign an array to pointer directly in C?
问题描述
我有以下程序。不过,我不明白为什么我要传递数组的地址。当它们都指向同一个地址。这为int的数组的第一个元素的地址。
I have the following program. However, I can't understand why I have to pass the address of the array. When they are both pointing to the same address. Which is the address of the first element of the array of int's.
我得到一个警告,当我尝试做这个从兼容的指针类型分配:
I get a warning when I try and do this "assignment from incompatible pointer type":
ptr = var;
完整源$ C $ C:
Complete source code:
void print_values(int (*ptr)[5])
{
size_t i = 0;
for(i = 0; i < 5; i++) {
printf("%d: [ %d ]\n", i, (*ptr)[i]);
}
}
int main(void)
{
/* declare a pointer to an array integers */
int (*ptr)[5] = NULL;
/* array of integers */
int var[] = {1, 2, 3, 4, 5};
/* assign the address of where the array is pointing to (first element) */
ptr = &var;
/* Both are pointing to the exact same address */
printf("var [ %p ]\n",(void*)var);
printf("&var [ %p ]\n", (void*)&var);
print_values(ptr);
return 0;
}
我编译code。与 GCC 4.4.4 C89 -Wall -Wextra -O0
推荐答案
这纯粹是一个类型的问题。
It's purely a type issue.
在最前pression上下文数组的名称(如 VAR
)衰变到一个指向数组的指针到初始元素,而不是的阵列。 [请注意,这并不意味着 VAR
是一个指针 - 它很是的不的指针 - 它只是的行为青霉>像的指针在最前pressions阵列的第一个元素。]
In most expression contexts the name of an array (such as var
) decays to a pointer to the initial element of the array, not a pointer to the array. [Note that this doesn't imply that var
is a pointer - it very much is not a pointer - it just behaves like a pointer to the first element of the array in most expressions.]
这意味着,在一个前pression VAR
正常衰减到一个指向 INT
,不一个指针数组 INT
。
This means that in an expression var
normally decays to a pointer to an int
, not a pointer to an array of int
.
作为操作数的地址运算符(&安培;
)就是这种衰减规律并不适用一个上下文(另一个是作为操作数的sizeof
运营商)。在这种情况下的类型&放大器; VAR
直接从类型衍生 VAR
这样的类型是指针数组5 INT
。
As the operand of the address-of operator (&
) is one context where this decay rule doesn't apply (the other one being as operand of the sizeof
operator). In this case the type of &var
is derived directly from the type of var
so the type is pointer to array of 5 int
.
是的,指针都具有相同的地址值(数组第一个元素的地址是阵列本身的地址),但他们有不同的类型(为int *
VS INT(*)[5]
),所以不在赋值兼容。
Yes, the pointers have the same address value (the address of an arrays first element is the address of the array itself), but they have different types (int*
vs int(*)[5]
) so aren't compatible in the assignment.
ISO / IEC 9899:1999 6.3.2.1/4:
ISO/IEC 9899:1999 6.3.2.1/4:
除非它是的sizeof
的运算数或一元&安培;
运营商,或者是一个字符串文字用于初始化数组,具有类型转换为类型的前pression指针输入指向初始元素的键入的数组的前pression数组对象是不是左值。 ...
Except when it is the operand of the
sizeof
operator or the unary&
operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression of type "pointer to type" that points to the initial element of the array object and is not an lvalue. ...
这篇关于为什么我不能将数组分配直接在C指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!