nakem
nakem

Reputation: 394

When casting void * to int, the address is passed, not the value

I have a struct t_args with void* types

typedef struct  s_args
{
    void    *width;
}   t_args;

I am passing in void * an int address. Next, we look at the value of t_args->width in the same function int *q = (int *)args->width;, it is 4, everything is correct. But as soon as I pass the struct to the "processing" function processing(args, arg, return_len); , then t_args->width turns into a huge number, as if it translates a hex address into int and writes it into int. In that case, why the first time I check the value of t_args->width, it displays everything correctly?

this is the function where everything works

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);
}

this is a function where t becomes trash

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);

this function which create struct

/*
**      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);
}

this is fill args->width

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

I'm writing an implementation of printf. The string "%05d" is received, the width Specifier is stored in void *

Upvotes: 0

Views: 142

Answers (1)

Alexey Bukin
Alexey Bukin

Reputation: 147

replace_star(args, arg) function incorrect. It probably gets integer pointer from va_arg instead of integer itself. If you want to get pointer you should malloc() some memory and store that int.

Please, give me link so I can prove it to you.

Upvotes: 0

Related Questions