【发布时间】:2023-01-25 01:29:12
【问题描述】:
char *ft_between(char *str, size_t from, size_t to)
{
char *between;
between = malloc(16);
while ((from >= 0) && (from < to) && (to < ft_strlen(str)))
{
*(between++) = str[from++];
}
*between = '\0';
printf("%s\n", between); // print nothing
printf("%s\n", between - 16); // print between but never had to do this before...
return (between);// even on calling function the pointer still at end of string
}
我认为这是因为我在使用 ++ 之间更改了地址,但我通常这样做并且从未有过这种行为......是因为 malloc 吗???
我错过了什么吗? 有一种方法可以“倒回”弦乐吗? 如果我通过柜台来做,即。之间[counter++] = str[from++];它有效,但我想通过指针来做,因为它更快......从我的红色!
在这个例子中 str 是用 ++ 迭代直到最后添加 char 但是当调用函数返回时,printf 将打印所有 str
void ft_nbr2str(char *str, size_t nbr, char *base, size_t base_len)
{
if (nbr >= base_len)
{
ft_nbr2str(str, (nbr / base_len), base, base_len);
while (*str != '\0')
str++;
*str = base[nbr % base_len];
}
else
*str = base[nbr];
}
【问题讨论】:
-
请 edit 您的问题,以显示在递增指针后按预期工作的代码示例。到目前为止您展示的代码完全符合我的预期。
-
你为什么打电话
strlen每一次通过循环?就此而言,(to < ft_strlen(str))应该是循环不变的,那么为什么它是while测试的一部分呢? -
如果您要更改
between,那么它将不再指向字符串的开头。保存原始值,然后使用它来检查(并返回)结果。 -
我会不是将
mallocarg 硬连线为 16。你是怎么得到的?你必须手动运行它才能弄清楚。我会在循环中使用realloc,这样您就可以进行精确控制,而不必“预测”16 的值。
标签: c substring dynamic-memory-allocation c-strings function-definition