如何返回在函数中创建的char数组? [英] How to return a char array created in function?

查看:132
本文介绍了如何返回在函数中创建的char数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编程不好已经有一段时间了,我才真正意识到。我以前创建了许多函数,这些函数将字符串作为char数组(或至少指向它们的指针)返回。

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).

前一天有人指出,当我的函数返回char时我的函数所指向的数组超出了范围,我现在实际上指向的是随机存储器(一个讨厌的悬空指针)。

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).

我没有真正注意到这一点是因为char数组在输出到控制台时似乎没有损坏(可能是因为没有时间覆盖该数据)。但是,当我返回通过读取经常损坏的串行端口生成的字符串缓冲区(char数组)时,确实注意到了这一点。

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?

我的错误代码如下:

#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.

此外,何时应该使用new []命令创建数组?需要吗?

Also, when should I use the new[] command to create my array? is it needed? and when should I call delete[] on it.

对此,我非常感谢,它显然非常基础,但是我做错了一段时间。

Many thanks for this, its obviously very fundamental but something I've been doing wrong for a while.

推荐答案

最简单的方法是返回 std :: string ,如果您需要使用 std :: string :: c_str()访问内部字符数组。

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().

#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;
}

如果需要返回除char数组以外的其他内容,请记住指针可以用作迭代器。这使您可以将数组封装在向量或类似的结构中:

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:

vector<int> returnInts() {
    int someNums[] = { 1, 2, 3, 4 };
    return vector<int>(someNums, someNums + 4);
}

这篇关于如何返回在函数中创建的char数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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