c - 为什么函数参数两边要加括号?

标签 c function parameters

我正在从程序员的角度学习计算机系统第 2.1 节,我了解代码的作用,但我不明白为什么形式参数“byte_pointer”周围有括号,后面跟着 &x?

typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer start, int len) {
    int i;
    for (i = 0; i < len; i++)
        printf(" %.2x", start[i]);
    printf("\n");
}

void show_float(float x) {
    show_bytes((byte_pointer) &x, sizeof(float));
}

void show_int(int x) {
    show_bytes((byte_pointer) &x, sizeof(int));
}

void show_pointer(void *x) {
    show_bytes((byte_pointer) &x, sizeof(void *));
}

最佳答案

您正在将 float 指针类型转换为 unsigned char*。然后您将访问浮点变量的每个字节。由于指针算术是由它所指向的事物的类型决定的 - 其增量或减量将由 sizeof(unsigned char)1 字节直接决定。您将逐字节访问 float 。通过强制转换,我们基本上是说您需要将其视为 unsigned char*,即使它是我们传递的 float*。类型信息发生了变化 - 我们通过提供强制转换让编译器意识到我们已经意识到了这一点。

关于c - 为什么函数参数两边要加括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276894/

相关文章:

c# - C++ 函数作为参数

c - 具有正确文件长度和缓冲区分配的 fread 段错误

C 一次读取4个字节

javascript - 为什么变量定义在JS中不是挂起而是函数

function - 纬度/经度 + 距离 + 航向 --> 纬度/经度

java - builder模式和大量强制参数

c - 交换链表中的相邻元素

c - 简单的C trie程序出错(段错误)

python - 接受标量或 numpy 数组作为参数的 python 函数

C#:组件的输出参数索引 [i] 过高或过低