使用指针反转 C 中的字符串?
语言:C
我正在尝试编写一个 C 函数,该函数使用标头 char *strrev2(const char *string) 作为面试准备的一部分,最接近的(工作)解决方案如下,但是我想要一个不包含 malloc 的实现……这可能吗?因为它返回一个字符,这意味着如果我使用 malloc,则必须在另一个函数中使用 free。
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;
}
[编辑] 我已经使用缓冲区而不使用字符编写了实现。谢谢你!
Language: C
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;
}
[EDIT] I have already written implementations using a buffer and without the char. Thanks tho!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不 - 你需要一个 malloc。
其他选项有:
const char *
并且不允许您更改函数签名,因此这里不可能这样做。No - you need a malloc.
Other options are:
const char *
and you aren't allowed to change the function signature, this is not possible here.您可以这样做,并让调用者负责
释放
内存。或者你可以允许调用者传入一个已分配的字符缓冲区,这样分配和释放都由调用者完成:对于调用者:
You may do it this way and let the caller responsible for
free
ing the memory. Or you can allow the caller to pass in an allocated char buffer, thus the allocation and the free are all done by caller:For caller:
您可以使用
static char[1024];
(1024 是示例大小),存储此缓冲区中使用的所有字符串并返回包含每个字符串的内存地址。以下代码片段可能包含错误,但可能会给您带来想法。You could use a
static char[1024];
(1024 is an example size), store all strings used in this buffer and return the memory address which contains each string. The following code snippet may contain bugs but will probably give you the idea.将字符串反转到位
reverse string in place