麻烦从返回函数的字符串 [英] Trouble with returning a string from function

查看:84
本文介绍了麻烦从返回函数的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有串C中的基本原则麻烦
我有一个函数:

I am having trouble with the basic principles of strings in C. I have a function:

char *editStr(char *str) {
char new[strlen(str)];
... do some editing ...
return new;
}

我如何将返回字符,也称新的数组。据我了解,该函数的返回值是一个char *,这意味着它是要求一个指向字符串的第一个字符。
现在,我想这个问题是我返回数组的一个字符。我试图指针在新返回的第一个字符,但似乎并没有工作,要么。
我想回归*新的[0]。
我的字符串的知识是坏的。

How would I return the array of characters called "new". As I understand, the return value of the function is a char*, which means that it is asking for a pointer to the first character of a string. Right now, I guess the problem is that I am returning a character of arrays. I tried to return a pointer to the first character in "new", but that doesn't seem to work, either. I tried "return *new[0]". My string knowledge is bad.

推荐答案

有这里有各种各样的问题,但与阵列/指针问题返回新; 不是之一它们。

There are various problems here but the array/pointer issue with return new; isn't one of them.

首先,你想要的:

char new[strlen(str) + 1];

,让你有足够的空间,空终止符。

So that you have enough room for the null terminator.

堆栈所以退回它只会造成悲痛和混乱分配;你会想:

Your new is allocated on the stack so returning it will only cause grief and confusion; you'll want to:

char *new = malloc(strlen(str) + 1);

代替该内存仍然有效,当函数返回。

instead so that the memory is still valid when the function returns.

至于你真正的问题去,在C数组的第一个元素的地址,所以你的返回新; 是罚款(受堆与堆问题上面指出)。 C数组衰减到在动不动指针,所以你不必担心,当函数声明为返回一个指针返回一个数组。

As far as your real question goes, an array in C is the address of the first element so your return new; is fine (subject to the stack versus heap issue noted above). C arrays decay to pointers at the drop of a hat so you don't need to worry about returning an array when the function is declared to return a pointer.

这篇关于麻烦从返回函数的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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