C++ 如何返回在函数中创建的字符数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3733582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a char array created in function?
提问by Zac
I've been programming badly for quite a while and I only really just realised. I have previously created many functions that return character strings as char arrays (or at least pointers to them).
很长一段时间以来,我一直在编程,但我才真正意识到。我之前创建了许多将字符串作为字符数组(或至少是指向它们的指针)返回的函数。
The other day someone pointed out that when my functions return the char arrays pointed to by my functions have gone out of scope and I'm essentially now pointing to a random bit of memory (A nasty dangling pointer).
前几天有人指出,当我的函数返回时,我的函数指向的字符数组超出了范围,我现在基本上指向了一个随机的内存位(一个讨厌的悬空指针)。
I didn't really notice this for a while because the char arrays when outputted to the console didn't appear to be corrupt (probably because there wasn't time for that data to be overwritten). I did however notice this when I was returning a string buffer (char array) generated by reading the serial port which was frequently corrupt.
我有一段时间没有真正注意到这一点,因为输出到控制台时的字符数组似乎没有损坏(可能是因为没有时间覆盖该数据)。但是,当我返回通过读取经常损坏的串行端口生成的字符串缓冲区(字符数组)时,我确实注意到了这一点。
So, how best should I do it?
那么,我应该怎么做最好呢?
My bad code is as follows:
我的错误代码如下:
#include <cstdlib>
#include <iostream>
using namespace std;
char* myBadFunction(){
char charArray[] = "Some string\n";
char* charPointer = charArray;
return charPointer;
}
int main(int argc, char** argv) {
cout << myBadFunction();
return 0;
}
I understand that I should perhaps allocate memory in the program before calling the function or create a global variable to put the returned string in, but if my called function is used by many different programs when how should it know the size of the buffer being passed into it in advance and when should this memory be deleted?
我知道我应该在调用函数之前在程序中分配内存或创建一个全局变量来放置返回的字符串,但是如果我被调用的函数被许多不同的程序使用,它应该如何知道正在传递的缓冲区的大小提前进入它,什么时候应该删除这段记忆?
The following code also doesn't do what I want it to properly:
以下代码也没有正确执行我想要的操作:
#include <cstdlib>
#include <iostream>
using namespace std;
void fillArray(char* charPointer){
char charArray[] = "Some string\n"; // Create string
charPointer = charArray; // Not correct, want to fill predefined array with created string
return;
}
int main(int argc, char** argv) {
char predefinedArray[50] = {0};
fillArray(predefinedArray);
cout << predefinedArray;
return 0;
}
I want to fill the array that the pointer parsed points to but this doesnt' happen in the code above.
我想填充指针解析指向的数组,但这不会在上面的代码中发生。
Also, when should I use the new[] command to create my array? is it needed? and when should I call delete[] on it.
另外,我什么时候应该使用 new[] 命令来创建我的数组?需要吗?我应该什么时候调用 delete[] 呢?
Many thanks for this, its obviously very fundamental but something I've been doing wrong for a while.
非常感谢这一点,这显然是非常基本的,但我已经做错了一段时间。
采纳答案by Paul
The simplest way would be to return a std::string
, and if you needed access to the internal char array use std::string::c_str()
.
最简单的方法是返回 a std::string
,如果您需要访问内部 char 数组,请使用std::string::c_str()
.
#include <iostream>
#include <string>
using namespace std;
string myGoodFunction(){
char charArray[] = "Some string\n";
return string(charArray);
}
int main(int argc, char** argv) {
cout << myGoodFunction();
return 0;
}
If you need to return something other than a char array, remember that pointers can be used as iterators. This allows you to encapsulate an array in a vector or a similar structure:
如果您需要返回 char 数组以外的内容,请记住指针可以用作迭代器。这允许您将数组封装在向量或类似结构中:
vector<int> returnInts() {
int someNums[] = { 1, 2, 3, 4 };
return vector<int>(someNums, someNums + 4);
}
回答by Alexander Rafferty
You have two options for returning an array in C++. You can fill in pre-allocated memory (good), or allocate your own within the function and return it (bad). The reason that the first is preferred is because it re-enforces proper disposal of allocated memory.
在 C++ 中返回数组有两种选择。您可以填充预先分配的内存(好),或者在函数内分配自己的内存并返回(坏)。首选第一个的原因是因为它重新强制正确处理分配的内存。
A basic example would look like this:
一个基本示例如下所示:
void fillArray(char* buffer, int sz) {
char text[] = "hello there!";
if (sizeof(text)>sz) {
// overflow! Buffer is too small!
return;
}
for (int n=0;n<sizeof(text);n++) {
buffer[n] = text[n];
}
}
int main() {
char* buffer = new char[30]; // allocates a buffer of 30 bytes.
fillArray(buffer,30);
cout << buffer;
delete [] buffer;
}
/* note that it would be easier to use static memory in this example */
It isn't hard when you think about the problem.
当你想到这个问题时,这并不难。
回答by Rambo
Declare the array as "static" varible and return with its address. This code works, but causes a warning :
将数组声明为“静态”变量并返回其地址。此代码有效,但会导致警告:
#include <cstdlib>
#include <iostream>
using namespace std;
char* myBadFunction(){
static char charArray[] = "Some string\n"; // insert "static"
// char* charPointer = charArray;
return charArray; // charArray is a pointer to the static array
} // after returning static varibles stay safe
int main(int argc, char** argv) {
cout << myBadFunction();
return 0;
}
回答by G. Brown
"Some string\n" is a string literal and will therefore exist for the lifetime of the program, so the following would be valid:
"Some string\n" 是一个字符串文字,因此将在程序的生命周期内存在,因此以下内容是有效的:
#include <cstdlib>
#include <iostream>
using namespace std;
char* myGoodFunction(){
char* charPointer = "Some string\n";
return charPointer;
}
int main(int argc, char** argv) {
cout << myGoodFunction();
return 0;
}
Of course this is only useful if the function always returns the same string. If the returned string can vary (generally the case) then you can declare the char array in your function as static and return it's address (as has already been suggested).
当然,这只有在函数总是返回相同的字符串时才有用。如果返回的字符串可能会有所不同(通常是这种情况),那么您可以将函数中的 char 数组声明为静态并返回它的地址(正如已经建议的那样)。