我正在做我在C中的第一次家庭作业,我正在努力掌握指针。它们在理论上是有道理的,但在执行中我有点模糊。我有这个代码,它应该取整数x,找到它的最低有效字节,并在同一位置用该字节替换y。 GCC返回:
“2.59.c:34:2:警告:传递'replace_with_lowest_byte_in_x'的参数1使得整数指针没有强制转换[默认情况下启用]
2.59.c:15:6:注意:预期'byte_pointer'但参数类型为'int'“
对于论点2也是如此。有人会非常友好地向我解释这里发生了什么吗?
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int length) {
int i;
for (i=0; i < length; i++) {
printf(" %.2x", start[i]);
}
printf("\n");
}
void replace_with_lowest_byte_in_x(byte_pointer x, byte_pointer y) {
int length = sizeof(int);
show_bytes(x, length);
show_bytes(y, length);
int i;
int lowest;
lowest = x[0];
for (i=0; i < length; i++) {
if (x[i] < x[lowest]) {
lowest = i;
}
}
y[lowest] = x[lowest];
show_bytes(y, length);
}
int main(void) {
replace_with_lowest_byte_in_x(12345,54321);
return 0;
}
答案 0 :(得分:3)
函数需要两个指针,但是你传递整数(-constant)s。您可能想要的是将数字放在它们自己的变量中并将这些数字的地址传递给函数:(在main
中):
int a = 12345, b = 54321;
replace_with_lowest_byte_in_x(&a, &b);
请注意,您仍然传递不兼容的指针。
答案 1 :(得分:2)
编译器是正确的,你的replace_with_lowest_byte_in_x()需要两个unsigned char *
,但你将两个int
传递给它。是的,int
可以被视为内存地址,但它很危险,所以有一个警告。 &variable
为您提供变量的地址。