数组指针(不是数组指针)是 C 编程语言的一个鲜为人知的功能。
int arr[] = { 3, 5, 6, 7, 9 };
int (*arr_ptr)[5] = &arr;
printf("[2]=%d", (*arr_ptr)[2]);
Run Code Online (Sandbox Code Playgroud)
它们允许您“恢复”动态分配的数组指针。
(我认为这很酷)
int *ptr = malloc(sizeof(int) * 5);
int(*arr_ptr)[5] = (int(*)[5])ptr;
printf("[2]=%d", (*arr_ptr)[2]);
Run Code Online (Sandbox Code Playgroud)
我试图定义一个函数来返回数组指针,但没有成功。
我尝试过这样的事情:
int (*)[5] create_arr_5(void)
{
int(*arr_ptr)[5] = malloc(sizeof(int) * 5);
return arr_ptr;
}
Run Code Online (Sandbox Code Playgroud) 作为练习,我正在尝试创建一个温度单位库。
目前,以下代码无法编译,并且我不清楚错误消息。问题似乎是类型冲突。
type Fahrenheit = f64;
type Celcius = f64;
type Kelvin = f64;
trait TemperatureUnit {
fn to_kelvin(&self) -> Kelvin;
}
impl TemperatureUnit for Fahrenheit {
fn to_kelvin(&self) -> Kelvin {
(*self + 459.67) * 5/9
}
}
impl TemperatureUnit for Celcius {
fn to_kelvin(&self) -> Kelvin {
*self + 273.15
}
}
impl TemperatureUnit for Kelvin {
fn to_kelvin(&self) -> Kelvin {
*self
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
error[E0119]: conflicting implementations of trait `TemperatureUnit` for type `f64`
--> src/lib.rs:18:1
| …Run Code Online (Sandbox Code Playgroud) 我正在尝试构建一个可以在没有任何动态内存分配的情况下填充结构的通用函数。
以下代码是我正在尝试做的事情的一个简单示例。此代码不会编译为incomplete type 'void' is not assignable.
请注意,这是一个突出我的问题的玩具示例。我真的不想转换颜色;我只想强调结构在数据类型和大小上会有所不同。
#include <stdio.h>
typedef struct {
int r;
int g;
int b;
} rgb_t;
typedef struct {
float c;
float m;
float y;
float k;
} cmyk_t;
typedef enum { RGB, CMYK } color_t;
void convert_hex_to_color(long hex, color_t colorType, void* const out) {
if (colorType == RGB) {
rgb_t temp = { 0 };
// Insert some conversion math here....
temp.r = 1;
temp.g = 2;
temp.b = 3; …Run Code Online (Sandbox Code Playgroud) 我正在尝试练习使用 Rust 的函数功能。
例如,我想转换这个循环:
levels: Vec<Vec<u8>> = //< Built by something
let mut total = 0;
for (x, y) in iproduct!(0..10, 0..10) {
if levels[x][y] > 9 {
total += count_something(levels, x, y);
}
}
// Edit: here's the `count_something` function signature
fn count_something (levels: &mut Vec<Vec<u8>>, x: usize, y: usize) -> usize {
// Count
}
Run Code Online (Sandbox Code Playgroud)
这是我的功能重构的结果:
iproduct!(0..10, 0..10)
.filter(|(x, y)| levels[*x][*y] > 9)
.map(|(x, y)| count_something(levels, x, y))
.sum()
Run Code Online (Sandbox Code Playgroud)
问题是:这段代码无法编译。
错误:error[E0500]: closure requires unique access to *levels …