【问题标题】:Cast a (void const *x) to a (unsigned char const *y)将 (void const *x) 转换为 (unsigned char const *y)
【发布时间】:2013-07-29 08:24:18
【问题描述】:

我正在通过一个源代码分析它的实现,我定义了一个方法:

unsigned int rs_calc_weak_sum(void const *p, int len) {
unsigned char const    *buf = (unsigned char const *) p;
}

什么类型的参数应该传入这个方法??

请帮帮我。

谢谢。

【问题讨论】:

  • 指向任何东西的指针。毕竟,这就是void* 的含义。
  • 应该还是可以?看起来它需要任何常量指针并将其重铸为无符号字符常量指针。这是它应该做的吗?
  • @Jim 谢谢。是的。我需要传递一个字符数组。你能给我举个例子吗?
  • @larsmans 谢谢。我明白了。我需要传递一个字符数组。请给我一个例子。
  • @Satthy:这是什么语言? C 还是 C++?

标签: methods types parameter-passing


【解决方案1】:

任何指针都可以传递给 void * 参数。 “应该”传递什么,取决于代码对该参数的作用。

char array[12] = "Hello World";
unsigned in res = 0;
res = rs_calc_weak_sum(array, 12);

#include <stdio.h>
int main ( void )
{
  char filename[] = "file.txt";
  FILE *file = fopen ( filename, "r" );

  if (file != NULL) {
    char line [1000];
    while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
      res = rs_calc_weak_sum(line, 1000);
    }

    fclose(file);
  }
  else {
    perror(filename); //print the error message on stderr.
  }

  return 0;
}

【讨论】:

  • 我需要使用 getc 从文件中获取字符块。然后我需要将该块传递给这个方法。请给我一些示例代码。谢谢。
  • 谢谢。这个我已经试过了。但它给了我一个错误,说“未定义对 rs_calc_weak_sum(void const*, int) 的引用”
  • 听起来像是链接器问题。你在做什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多