You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归实现C语言printf指针打印时返回值异常求助

递归打印地址计数错误的问题解决

你的问题核心出在print_hex函数的递归调用处理上:你执行了递归,但完全没把递归返回的字符数累加到counter里。每次递归层只会统计自己写入的1个字符长度,上层完全忽略了递归产生的输出,所以print_hex永远返回1,最终导致总计数错误。

另外你的递归判断条件nb > 9逻辑有问题——十六进制每一位是0-15,只有当数值大于等于16时才需要拆分高位,否则直接打印当前位即可。原来的条件会让10-15的数触发递归,导致多打印一个前导0,不符合地址打印的预期。

修正后的代码

int ft_print_address(long unsigned int nb)
{
    int     counter;

    if (nb == 0)
        return(write(1, "(nil)", 5));
    else
    {
        counter = write(1, "0x", 2);
        counter += print_hex(nb);
        return (counter);    
    }
}

static int print_hex(long unsigned int nb)
{
    int         counter;
    char    *hex;

    counter = 0;
    hex = "0123456789abcdef";
    // 修正判断条件:只有当数值>=16时才递归拆分高位
    if (nb >= 16) 
    {
      // 累加递归调用返回的字符数
      counter += print_hex(nb / 16);
    }
    counter += write(1, &hex[nb % 16], 1);
    return (counter);
}

修正说明

  1. 计数累加修复:把print_hex(nb / 16);改为counter += print_hex(nb / 16);,这样每一层递归返回的字符数都会被累加到当前层的counter中,最终返回的是整个十六进制字符串的总长度。
  2. 递归条件修正:将nb > 9改为nb >= 16,确保只有当数值需要拆分高位时才触发递归,避免10-15的数错误打印前导0。

内容的提问来源于stack exchange,提问作者pedrooc16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:01:20