【发布时间】:2020-11-30 23:27:59
【问题描述】:
我有一个 struct t_args 和 void* 类型
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_star和create_struct函数。args初始化在哪里?args->width在哪里初始化?它指向哪里?这个函数是怎么调用的? -
这真的像一个悬空指针问题。
args->with指向什么,int发生了什么? -
请在代码的哪一行指出正确的值,以及错误的值。顺便说一句,在
printf的实现中调用malloc可能不是最好的主意。
标签: c