我目前正在尝试完成我的一门大学课程的家庭作业,但被卡住了。
#include <stdio.h>
void add(int *a[], const int *b[], const int *c[], int size); /* Function Prototype */
int main() {
int a[5];
const int b[] = {1,2,3,4,5};
const int c[] = {1,1,1,1,1};
add(a,b,c,5);
for(int i=0; i < 5; i++) {
printf("%d\t", a[i]);
}
return 0;
}
void add(int *a[], const int *b[], const int *c[], int size) {
for (int i = 0; i < size; i++) {
a[i]=b[i]+c[i];
}
}
我试图让函数add接收其参数作为指针而不是int数组。我已经咨询过教科书以及一些同行的教科书,但我仍然普遍感到困惑。如果有人可以请问一下为什么我的上述实现不起作用?
这些是我得到的错误:
main.c: In function 'main':
main.c:9:7: warning: passing argument 1 of 'add' from incompatible pointer
type [-Wincompatible-pointer-types]
add(a,b,c,5);
^
main.c:3:6: note: expected 'int **' but argument is of type 'int *'
void add(int *a[], const int *b[], const int *c[], int size); /* Function
Prototype */
^~~
main.c:9:9: warning: passing argument 2 of 'add' from incompatible pointer
type [-Wincompatible-pointer-types]
add(a,b,c,5);
^
main.c:3:6: note: expected 'const int **' but argument is of type 'const int *'
void add(int *a[], const int *b[], const int *c[], int size); /* Function
Prototype */
^~~
main.c:9:11: warning: passing argument 3 of 'add' from incompatible pointer type [-Wincompatible-pointer-types]
add(a,b,c,5);
^
main.c:3:6: note: expected 'const int **' but argument is of type 'const int *'
void add(int *a[], const int *b[], const int *c[], int size); /* Function
Prototype */
^~~
main.c: In function 'add':
main.c:19:14: error: invalid operands to binary + (have 'const int *' and 'const int *')
a[i]=b[i]+c[i];
~~~~^~~~~
exit status 1
根据C标准(6.7.6.3函数声明符(包括原型))
7参数声明为“类型数组”应调整为“类型的合格指针”,其中类型限定符(如果有)是在数组类型派生的[和]中指定的那些。如果关键字static也出现在数组类型派生的[和]中,则对于函数的每次调用,相应实际参数的值应提供对数组第一个元素的访问,该元素至少具有指定数量的元素通过大小表达式。
因此这些函数声明声明相同的一个函数
void add(int a[5], const int b[5], const int c[5], int size);
void add(int a[5], const int b[10], const int c[15], int size);
void add(int a[], const int b[], const int c[], int size);
并且等同于声明
void add(int *a, const int *b, const int *c, int size);
考虑到根据相同的C标准,main
不带参数的函数应声明为
int main( void )
将魔术“原始”数字设为5也是一个坏主意。
该程序可以看起来像
#include <stdio.h>
void add( int *a, const int *b, const int *c, size_t size); /* Function Prototype */
#define N 5
int main( void )
{
int a[N];
const int b[N] = { 1, 2, 3, 4, 5 };
const int c[N] = { 1, 1, 1, 1, 1 };
add( a, b, c, N );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d\t", a[i] );
}
return 0;
}
void add( int *a, const int *b, const int *c, size_t size )
{
for ( size_t i = 0; i < size; i++ )
{
a[i] = b[i] + c[i];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句