gpt4 book ai didi

c - 初学者的指针(带代码)

转载 作者:太空宇宙 更新时间:2023-11-04 06:01:14 25 4
gpt4 key购买 nike

我正在用 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;
}

最佳答案

该函数需要两个指针,但您传递的是整数(-常数)。您可能想要的是将数字放入它们自己的变量中,并将它们的地址传递给函数:(在 main 中):

int a = 12345, b = 54321;

replace_with_lowest_byte_in_x(&a, &b);

请注意,您仍在传递不兼容的指针。

关于c - 初学者的指针(带代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19215738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com