在C数组指针的试验 [英] Experimenting with pointers of arrays in C
问题描述
我有一个数组 A
,其值我想通过另一个函数修改。这是code,我有:
I have an array a
whose values I wish to modify through another function. This is the code that I have:
#include "stdlib.h"
#include "stdio.h"
void myfunc(int* );
int main() {
int *a, i;
a = (int*) calloc(10,sizeof(int));
myfunc(&a);
for (i=0; i<10; i++) printf("%d\n", a[i]);
return 0;
}
void myfunc(int* a) {
int i;
for (i=0; i<10; i++) *a[i] = i;
}
显然东西是错误与我的语法,我想知道,如果有人可以帮我一把:)
Obviously something is wrong with my syntax and I Was wondering if someone could lend me a hand :)
谢谢!
推荐答案
在主函数中,你已经有了一个指向一个整数, A
。那么你该指针的地址传递给 MYFUNC
,但 MYFUNC
期待一个指向一个int,而不是一个指针一个指针为int。您需要将到 MYFUNC
通话改成这样:
In the main function, you've got a pointer to an integer, a
. Then you pass the address of this pointer to myfunc
, but myfunc
is expecting a pointer to an int, not a pointer to a pointer to an int. You need to change your call to myfunc
to this:
myfunc(a);
不过,你也有内部的 MYFUNC
的一个问题。你不需要解引用 A [I]
因为这指数到一个数组 A
。这些都是(有效),同样的事情:
But, you've also got a problem inside myfunc
. You don't need to dereference a[i]
since that indexes into an array a
. These are (effectively) the same thing:
a[i]
和
*(a+i)
(这是不是100%,我认为,因为在C指针和数组不完全一样的东西,所以一些专家的C程序员可以指正)
(This isn't 100%, I think, because in C pointers and arrays are not completely the same thing, so some expert C programmer can correct me)
你可能只是得到一个有点绕指针和数组语法的收集困惑:
You're probably just get a bit confused by the collection of syntax around pointers and arrays:
&a
*a
a[i]
*(a+i)
第一个是 A
,第二个指针引用 A
为指针,第三个是一个地址索引到一个数组,第四个是取消引用 A
与指针的偏移量。
The first one is the address of a
, the second dereferences a
as a pointer, the third is an index into an array and the fourth is dereferencing a
as a pointer with an offset.
您只需要做到这一点 *(A [])
如果你有一个指针数组,而不是一个指针为int。
You would only want to do this *(a[i])
if you had an array of pointers, not a pointer to an int.
这篇关于在C数组指针的试验的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!