【问题标题】:Creating variable with String to pass as uchar*使用字符串创建变量以作为 uchar* 传递
【发布时间】:2013-03-18 18:17:52
【问题描述】:

我正在编写一个将文本传递给库函数的程序。 此函数要求文本参数的类型为 unsigned char*.

那么我怎样才能正确地将字符串传递给该函数呢?我无法将现有的 char* 转换为 unsigned char* 并通过 strncpyunsigned char* 变量/em> 也没有用。

编辑: 这是一个小例子:

这就是我需要调用的函数:

int count (void *index, uchar *pattern, uint length, uint *numocc);

这是我的代码中的内容:

count(index,?argv[2]?, length, numocc);

【问题讨论】:

  • 请提供一个简单的例子来说明您遇到的问题。

标签: c types


【解决方案1】:

您可以使用(unsigned char*) 进行类型转换。我发布一个小例子可能对你有帮助(阅读 cmets):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void func(unsigned char* str){ // argument should be unsigned char*
    printf("\n In side fun:  %s\n", str);
}
int main(){
    char* s = "your_name"; // s is char* 
    func((unsigned char*)s);  // notice type casting
    return 1;
}

它的工作原理:

~$ gcc x.c  -Wall
~$ ./a.out 

 In side fun:  your_name
~$ 

编辑

count(index, (uchar*)argv[2], length, numocc);  
               ^ typecast (uchar*)

uchar* 可能是您代码中的类型定义,例如:

typedef unsigned char* uchar*

【讨论】:

  • 谢谢,成功了。我认为只是投射这个并不会真正改变内部表示,但实际上它确实改变了。
猜你喜欢
  • 1970-01-01
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 1970-01-01
  • 2020-01-28
  • 2011-10-22
相关资源
最近更新 更多