小编Tim*_*gan的帖子

C指针和指针传递指针

我正在努力学习C语言,而且我在指针指针上挂了一点.我想我理解你为什么需要它们,但不能完全理解正在发生的事情.

例如,以下代码似乎不像我期望的那样工作:

#include <stdio.h>

int newp(char **p) {
  char d = 'b';
  *p = &d;
  /*printf("**p = %c\n", **p);*/
  return 1;
}

int main() {
  char c = 'a';
  char *p = &c;
  int result;

  result = newp(&p);
  printf("result = %d\n", result);
  printf("*p = %c\n", *p);
  printf("c = %c\n", c);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到的结果是这样的:

result = 1
*p = 
c = a
Run Code Online (Sandbox Code Playgroud)

*p打印为空.相反,我希望*p = b.

但是,如果我取消注释第6行(printfnewp函数中),那么我得到这个:

**p = b
result = 1
*p …
Run Code Online (Sandbox Code Playgroud)

c pointers

6
推荐指数
2
解决办法
4360
查看次数

如何使用map(功能而非命令性)返回盒装特征的向量

我是Rust的新手,我只是刚刚开始掌握一些核心概念.

就我而言,我需要返回一个盒装特征向量.我想在函数式编程风格中做到这一点,但我无法编译它.

有人解释为什么下面的代码在我使用for循环(命令式样式)时有效,但在使用迭代器(filter_map在这种情况下)使用函数式编程样式时不起作用?

注意:这是一个人为的例子,并且已经简化为我能写的最简单的形式,以证明我的误解.

#![allow(unused_variables)]

struct Foo {}
struct Bar {}

trait Thing {}

impl Thing for Foo {}
impl Thing for Bar {}

fn main() {
    let things = get_things_using_for_loop(); // works!
    let things = get_things_using_iterator(); // doesn't work! :-(
}

fn get_things_using_for_loop() -> Vec<Box<Thing>> {
    let mut things: Vec<Box<Thing>> = vec![];
    for t in ["foo".to_string(), "bar".to_string()].iter() {
        if t == "foo" {
            things.push(Box::new(Foo {}))
        } else if t == "bar" {
            things.push(Box::new(Bar {})) …
Run Code Online (Sandbox Code Playgroud)

traits rust

3
推荐指数
2
解决办法
436
查看次数

标签 统计

c ×1

pointers ×1

rust ×1

traits ×1