【发布时间】:2013-07-03 01:03:53
【问题描述】:
在C99中,为什么在将变量p声明为指向数组的指针之前需要将其作为参数传递给具有数组类型参数的函数,而将变量p声明为void指针然后将其转换为指向数组的指针可以作为指向数组的指针传递给同一个函数吗?
#include <stdio.h>
int arreglo(int locArr[])
{
locArr[0]=1;
printf("el arreglo es : %i\n",locArr[0]);
return 0;
}
int main()
{
/* Declare a pointer p to array */
int (*p)[];
int manArr[10];
p=&manArr; /* assign the adress of manArr as case below */
/* Here passing pointer p is not allowed as expected,
since our function has int* as argument */
/* so I need to do a casting */
arreglo((int*)p);
}
/* **But in this other main function**: */
int main()
{
/* Declare a void pointer */
void *p=NULL;
/* Do a casting from p to void to p to array */
p=(int (*)[])p;
int manArr[10];
p=&manArr; /* assing the adress of the array manArr as in above case */
/* Now given the pointer to array as parameter to function WORKS¡¡,
why?. As before the function expects int* as argument not
a pointer to an array */
arreglo(p);
}
【问题讨论】:
-
问题是:为什么它在第二个主要功能中起作用。根据 C 参考,当您将数组作为参数时,它将转换为指向 int (int*) 的指针,因此 int* arr 与 int arr[] 相同(仅在参数列表上)。但是如果你在理论上传递一个指向 Array 的指针,你需要将它转换为 int*。
-
这听起来很迂腐,但我真的很想帮忙。您应该尝试将您的问题放在一个句子中,并以
"<question-word> ... ?"的问题形式提出。一旦您明确了问题的确切含义,回答起来就会容易得多。在本练习中,您可能会自己发现答案。 ...首先,请确保您确切了解这些术语的含义:指向 int 的指针、int 数组、指向数组的指针。 ...混淆:融合在一起,解决方案是严格澄清和限定所涉及的不同概念。 -
感谢您的建议,这是我在本站的第二个问题。
-
+1 学习和改进!欢迎来到本站!
标签: c arrays function casting arguments