从没有使用strcpy的强制转换的整数生成指针

我无法弄清楚我做错了什么。 我正在学习C很抱歉,如果这显然是错误的,但我正在尝试使用uthash来制作股票及其价格的哈希图。 但是当我向哈希地图添加股票时,我得到了上述错误。

我所做的是从他们的网站上获取示例并运行它以确保它工作,一旦它按预期工作我改变了值以适应我的问题。 在原始代码中,结构中的变量id是一个整数,但我将其更改为char(而不是数字,我想使用股票代码作为键),然后我开始出现以下错误:

 ../src/stackCsamples.c:87: warning: passing argument 1 of '__builtin_object_size' makes pointer from integer without a cast ../src/stackCsamples.c:87: warning: passing argument 1 of '__builtin_object_size' makes pointer from integer without a cast ../src/stackCsamples.c:87: warning: passing argument 1 of '__builtin___strcpy_chk' makes pointer from integer without a cast ../src/stackCsamples.c:87: warning: passing argument 1 of '__inline_strcpy_chk' makes pointer from integer without a cast ../src/stackCsamples.c:89: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast ../src/stackCsamples.c:89: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast ../src/stackCsamples.c:89: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast 

问题似乎是这里有两行(87)是strcpy(s->id, user_id); (89)其中: HASH_ADD_STR( users, id, s );

我怎么用这两个错了? 我看起来strcpy起来,它看起来需要3个项目,但是当我添加大小时,我仍然会收到错误。

以下是我认为相关的部分片段:

 #include  /* gets */ #include  /* atoi, malloc */ #include  /* strcpy */ #include "uthash.h" struct my_struct { char id; /* key */ float price; UT_hash_handle hh; /* makes this structure hashable */ }; struct my_struct *users = NULL; void new_stock(char *user_id, float price) { struct my_struct *s; s = (struct my_struct*)malloc(sizeof(struct my_struct)); strcpy(s->id, user_id); s->price = price; HASH_ADD_STR( users, id, s ); /* id: name of key field */ } int main() { printf("starting.."); new_stock("IBM", 10.2); new_stock("goog", 2.2); return 0; } 

您需要在结构中为用户ID数组提供足够的空间,或者动态分配足够的空间。 例如,您可能会这样做:

 enum { MAX_ID_LEN = 32 }; struct my_struct { char id[MAX_ID_LEN]; /* key */ float price; UT_hash_handle hh; /* makes this structure hashable */ }; 

然后你可以使用:

 strcpy(s->id, user_id); 

只要你检查过user_id不超过31个字符加上空前的null。 如果你没有做那个检查,你应该。 如果您拒绝执行该检查并且不介意截断超长用户ID字符串,那么您可以使用:

 strncpy(s->id, user_id, sizeof(s->id) - 1); s->id[sizeof(s->id)-1] = '\0'; 

这确保了空终止; 仅仅使用strncpy()不会。 请注意,如果字符串( s->id )更长,您可能会发现您的代码浪费时间将字符串的尾端清零。


关于strlen()的剩余警告被HASH_ADD_STR()宏隐藏,但可能来自与strcpy()警告相同的问题 – s->id字段不是字符指针或字符数组。 修改后的结构也可能会消除这些警告。 对于我们来说,您必须显示HASH_ADD_STR()的定义以及它调用的任何宏。

有了这条线:

 strcpy(s->id, user_id); 

您正在尝试将字符串复制到char上。 请注意,strcpy的两个参数都是指向 chars: char * 指针

此外,请注意,您还需要在内存中为s-> id创建一些空间,作为char[]char * 。 提示:你已经为结构创建了空间,但是只包含了id单个字符的足够空间。

如果您想使用C,那么您应该获得K&R的副本,但如果不这样做,您可能会花一些时间来审核它 。