c - 使用 strcpy 从整数生成指针,无需进行强制转换

标签 c

我不知道我做错了什么。我正在学习 C,如果这明显是错误的,很抱歉,但我正在尝试使用 uthash制作股票及其价格的 HashMap 。但是当我将股票添加到 HashMap 时,出现上述错误。

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

../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 <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;
}

最佳答案

用这一行:

strcpy(s->id, user_id);

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

此外,请注意,您还需要在内存中为 s->id 腾出一些空间,作为 char[]char *。提示:您已为结构留出空间,但这仅包含足够的空间用于 id单个字符

如果您想使用 C,那么您应该获取 K&R 的副本,但如果做不到这一点,您可能会花一些时间查看 this .

关于c - 使用 strcpy 从整数生成指针,无需进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891012/

相关文章:

c - Arduino函数绝对数组?

c - Qsort 与哈夫曼树

c - 使用 wait4() 的 Rusage 不显示已完成子进程的 CPU 时间

c - 如何测试文本文件中的十六进制字符串?

c - 一些我无法理解的简单 C 代码 - 互斥锁在这里做什么?

c - 编写一个测量缓存 block 大小的 C 程序

c - 分配指针与 memcpy/memmove

c++ - 段错误重载运算符 <<