编译器显示错误消息“从整数生成指针而不进行强制转换". (反转数组).我该如何解决? [英] Compiler shows the error message "makes pointer from integer without cast" (reversing an array). How do i resolve this?
问题描述
代码如下.调用函数reverse_array时,如何将第一个函数参数定义为数组?
The code goes as follows. while calling the function reverse_array, How do I define the first function argument as an array?
#include <stdio.h>
void swap(int* a, int* b);
void reverse_array(int a[], int n) {
int* b = a + n - 1;
while (b > a) {
swap(a, b);
a = a + 1;
b = b - 1;
}
}
void swap(int* ptra, int* ptrb) {
int t;
t = *ptra;
*ptra = *ptrb;
*ptrb = t;
}
main() {
int b[5] = { 1,2,3,4,5 };
reverse_array(b[5], 5);
int x;
for (x = 0; x < 5; x++) {
printf("%d", b[x]);
}
}
推荐答案
编译器显示错误消息使指针从整数生成而不进行强制转换"(反转数组).我该如何解决?
请勿将int
传递到期望指针的位置. :)
Do not pass an int
to where a pointer is expected. :)
背景:
在函数定义的上下文中,类似int a[]
的内容与int * a
相同,因此a
是指向int
的指针.
In the context of a function definition something like int a[]
is the same as int * a
, so a
is a pointer to int
.
您的呼叫者传递了b[5]
,这是int
-数组b
的第六个元素,因此它是int
(并且顺便说一句,越界访问,就像在C数组中是b
的元素可通过0到4之间的索引来寻址.
You caller passes b[5]
, which is the 6th element of the int
-array b
, so it's an int
(and BTW an out-of-bound access, as in C array are 0
-based so b
's element are addressed via indexes ranging from 0 to 4.
要传递"数组,只需给出b
.
To "pass" the array just give b
.
reverse_array(b, 5);
然后,数组b
将被衰减到其第一个元素的地址.此地址在函数中作为值a
接收.
The array b
would then be decayed to the address of its 1st element. This address is received within the function as value a
.
这篇关于编译器显示错误消息“从整数生成指针而不进行强制转换". (反转数组).我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!