使用指针反转C中的字符串? [英] Reversing a string in C using pointers?

查看:40
本文介绍了使用指针反转C中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

语言:C

我正在尝试编写一个 C 函数,它使用头文件 char *strrev2(const char *string) 作为面试准备的一部分,最接近的(工作)解决方案如下,但是我想要一个不包含 malloc 的实现... 这可能吗?如果我使用 malloc,它会返回一个字符含义,因此必须在另一个函数中使用 free.

I am trying to program a C function which uses the header char *strrev2(const char *string) as part of interview preparation, the closest (working) solution is below, however I would like an implementation which does not include malloc... Is this possible? As it returns a character meaning if I use malloc, a free would have to be used within another function.

char *strrev2(const char *string){
    int l=strlen(string);
    char *r=malloc(l+1);
    for(int j=0;j<l;j++){
        r[j] = string[l-j-1];
    }
    r[l] = '\0';
    return r;
}

我已经使用缓冲区编写了不带字符的实现.谢谢你!

I have already written implementations using a buffer and without the char. Thanks tho!

推荐答案

不 - 你需要一个 malloc.

No - you need a malloc.

其他选项是:

  • 修改字符串in-,但由于您有一个 const char * 并且您不能更改函数签名,所以这里不可能.
  • 添加一个参数,以便用户提供一个缓冲区来写入结果,但如果不更改签名(或使用全局变量,这是一个非常糟糕的主意),这也是不可能的.
  • Modify the string in-place, but since you have a const char * and you aren't allowed to change the function signature, this is not possible here.
  • Add a parameter so that the user provides a buffer into which the result is written, but again this is not possible without changing the signature (or using globals, which is a really bad idea).

这篇关于使用指针反转C中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆