如何通过引用将size_t参数传递给函数,并在C编程中返回结果

时间:2015-10-02 17:28:35

标签: c

我正在尝试在C中实现一个简单的哈希函数,并且鉴于我的大部分编程知识都是用Java编写的,我需要一些帮助。我使用以下typedef语句定义了size_t:

typedef unsigned int size_t;

然后我继续定义一个简单的;真的是哈希函数的占位符。

size_t hash(char const *input) {

    const int ret_size = 32;
    size_t ret = 0x555555;
    const int per_char = 7;

    while (*input) {
            ret ^= *input++;
            ret = ((ret << per_char) | (ret >> (ret_size - per_char)));
    }
    return ret;
}

然后我在代码的main()部分使用了函数,如下所示:

 size_t myInput = 546;
 size_t myHash;
 ...
 myHash=hash(&myInput);

但是我收到编译错误说明:

warning: passing argument 1 of 'hash' from incompatible pointer type [enabled by default]
error, forbidden warning: tos1.c:52

我做错了什么?我该如何解决?

反馈是正确的,并解决了我的问题。一旦我被允许并感谢,我会将评论标记为答案。

2 个答案:

答案 0 :(得分:2)

您不需要定义size_t;它应该已经定义了。

问题是您的函数定义采用const char *参数,但您使用size_t *类型的值调用它;类型不兼容。

您的输入应该是某种字符串,例如

char input[] = "This is a test";
...
myHash = hash( input );

请记住,C字符串只是由0值字节终止的字符值序列;它们存储char(或宽wchar_t的数组),但并非所有char数组都包含字符串。

答案 1 :(得分:0)

如果要使用任何类型的参数调用函数,可以编写原型,例如memcpy()memset()。也就是说,

#include <stdint.h>
#include <string.h>

typedef uint_fast32_t hash_t;
hash_t hash( const void* src, size_t size )
{
  const uint8_t* p = (const uint8_t*)src;
  /* We can dereference p now and do pointer arithmetic with it. */
  /* … */
}

extern struct data_t foo;
extern const char* message;

hash_t value = hash( &foo, sizeof(foo) );
hash_t string_hash = hash( message, strlen(message) );