gpt4 book ai didi

c - 为什么我不能直接在 C 中将数组分配给指针?

转载 作者:太空狗 更新时间:2023-10-29 16:42:44 26 4
gpt4 key购买 nike

我有以下程序。但是,我不明白为什么我必须传递数组的地址。当它们都指向同一个地址时。这是 int 数组的第一个元素的地址。

当我尝试执行此“来自不兼容指针类型的分配”时收到警告:

ptr = var;

完整的源代码:

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;
}

我用gcc 4.4.4 c89 -Wall -Wextra -O0编译代码

最佳答案

这纯粹是类型问题。

在大多数表达式上下文中,数组的名称(例如 var)会衰减为指向数组初始元素的指针,而不是指向数组的指针。 [请注意,这并不意味着 var 是一个指针 - 它非常不是一个指针 - 它只是表现像一个指向大多数表达式中数组的第一个元素。]

这意味着在表达式中 var 通常会衰减为指向 int 的指针,而不是指向 int 数组的指针。

作为地址运算符 (&) 的操作数是此衰减规则不适用的一个上下文(另一个作为 sizeof 的操作数)运算符(operator))。在这种情况下,&var 的类型直接派生自 var 的类型,因此该类型是指向 5 个 int 数组的指针。

是的,指针具有相同的地址值(数组第一个元素的地址是数组本身的地址),但它们具有不同的类型(int* vs int( *)[5]) 所以在作业中不兼容。

ISO/IEC 9899:1999 6.3.2.1/4:

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 - 为什么我不能直接在 C 中将数组分配给指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3504506/

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