【问题标题】:When casting void * to int, the address is passed, not the value将 void * 转换为 int 时,传递的是地址,而不是值
【发布时间】:2020-11-30 23:27:59
【问题描述】:

我有一个 struct t_argsvoid* 类型

typedef struct  s_args
{
    void    *width;
}   t_args;

我正在传递void * 一个int 地址。接下来我们看t_args->width在同一个函数int *q = (int *)args->width;中的值,是4,一切都正确。但是一旦我将结构传递给“处理”函数 processing(args, arg, return_len); ,然后 t_args->width 就会变成一个巨大的数字,就好像它将十六进制地址转换为 int 并将其写入 int。既然如此,为什么我第一次检查t_args->width的值时,一切都显示正确?

这是一切正常的功能

void        work_with_one_argument(int *i, char *str, va_list *arg, int *return_len)
{
    t_args *args;

    *i += 1;
    if (str[*i] == '%')
    {
        ft_putchar(str[*i]);
        *i += 1;
        *return_len += 1;
    }
    create_struct(&args, i, str);
    replace_star(args, arg);
    int *q = (int *)args->width;
    processing(args, arg, return_len);
}

这是t变成垃圾的函数

void            processing(t_args *args, va_list *arg, int *return_len)
{
    char *types;

    types = "diucpsxXnfge";
    int *t = (int *)args->width;
    if (!ft_memcmp(args->type, (void *)&types[0], 1) || \
            !ft_memcmp(args->type, (void *)&types[1], 1) || \
            !ft_memcmp(args->type, (void *)&types[2], 1))
        select_handler_int_unsign(args, arg, return_len, types);

这个创建结构的函数

/*
**      Function:         t_args        create_struct()
**
**      Description:      function create and fill struct t_args
*/

void            create_struct(t_args **args, int *i, char *str)
{
    *args = (t_args *)malloc(sizeof(t_args));
    struct_initialization(args);
    parse_specificators(args, i, str);
}

这是填充参数->宽度

/*
**      Function:         void      parse_spec_width()
**
**      Description:      parse width from string
*/

void            parse_spec_width(t_args **args, int *i, char *str)
{
    t_args  *tmp;
    char    *star;
    int     width;

    tmp = *args;
    star = "*";
    if (str[*i] == *star)
    {
        tmp->width = (void *)&star[0];
        *i += 1;
        return ;
    }
    if (str[*i] >= '0' && str[*i] <= '9')
    {
        width = ft_atoi(&str[*i]);
        tmp->width = (void *)&width;
        while (str[*i] >= '0' && str[*i] <= '9')
            *i += 1;
    }
}

我正在编写 printf 的实现。接收到字符串“%05d”,宽度说明符存放在void *

【问题讨论】:

  • 请将代码显示为说明问题的完整程序。也就是说,提供minimal verifiable example
  • 请创建一个完整程序,最多包括一个简短的main() 并包括所有相关的#includes。请显示replace_starcreate_struct 函数。 args 初始化在哪里? args-&gt;width 在哪里初始化?它指向哪里?这个函数是怎么调用的?
  • 这真的像一个悬空指针问题。 args-&gt;with 指向什么,int 发生了什么?
  • 请在代码的哪一行指出正确的值,以及错误的值。顺便说一句,在 printf 的实现中调用 malloc 可能不是最好的主意。

标签: c


【解决方案1】:

replace_star(args, arg) 函数不正确。 它可能从 va_arg 而不是整数本身获取整数指针。如果你想获得指针,你应该 malloc() 一些内存并存储该 int。

请给我链接,以便我向你证明。

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多