【发布时间】:2012-06-09 02:22:49
【问题描述】:
我不知道我做错了什么。如果这显然是错误的,我正在学习 C 很抱歉,但我正在尝试使用 uthash 制作股票及其价格的哈希图。但是当我将股票添加到我的哈希图中时,我得到了上述错误。
我所做的是从他们的网站上获取示例并运行它以确保它正常工作,一旦它按预期工作,我更改了值以适应我的问题。在原始代码中,struct中的变量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 个项目,但是当我添加大小时,我仍然得到错误。
这是我认为相关的部分的 sn-p:
#include <stdio.h> /* gets */
#include <stdlib.h> /* atoi, malloc */
#include <string.h> /* 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;
}
【问题讨论】:
-
什么是
user_id?它是如何定义的?还有HASH_ADD_STR是怎么定义的? -
@Als 抱歉,我不确定我是否理解,我认为在这种情况下 user_id 只是我传递给函数的变量的名称,在这种情况下是“IBM”还是“好”?我认为
HASH_ADD_STR是 uthash 中包含的宏。它最初是 HASH_ADD_INT 但我将其更改为 str 因为我的主键不是 int。 -
strcpy获取目标地址和源字符串,该函数假定目标足够大以容纳字符串。在您的情况下,目标是char,而源可能是字符串,您无法将字符串复制到 char,char(1 byte) 中没有足够的内存来保存字符串。您可以将一个 char 分配给另一个不需要复制的字符。 -
@Als 你的权利..我没有意识到..我知道 INT 等的大小。我只是错误地认为 chars 也有自然的大小并没有意识到那 python/java 正在为我调整它。感谢您的帮助。
标签: c