繁体   English   中英

为什么C ++为动态数组分配如此大的内存空间?

[英]Why is C++ allocating such a large space in memory for my dynamic array?

在尝试将其初始化为char数组之前,将readFruit.name初始化为NULL 我输入了size来查看是否是罪魁祸首,但这取决于我的输入。 无论tempString长度是tempStringreadFruit.name都会在内存中分配约25个“字符”,它们都是垃圾。 为什么不为它分配一个tempString.length()大小的空间,我该如何解决呢?

相关CPP

std::istream & operator>>(std::istream &is, Fruit &readFruit)
{

string tempString;
is >> tempString;
int size = tempString.length();
readFruit.name = new char[tempString.length()];
for(int i = 0; i < (int)tempString.length(); i++)
{
    readFruit.name[i] = tempString[i];
}
for(int i =0; i < CODE_LEN; i++)
{
    is >> readFruit.code[i];
}
return is;
}

相关H文件(构造函数)

#ifndef _FRUIT_H
#define _FRUIT_H
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
enum { CODE_LEN = 4 }; 
enum { MAX_NAME_LEN = 30 };
class Fruit
{
private:
    char *name;
    char code[CODE_LEN];
public:
    Fruit(const Fruit &temp);
    Fruit(){name = NULL;};
    bool operator<(const Fruit& tempFruit);
    friend std::ostream & operator<<(std::ostream &os, const Fruit& printFruit);
    bool operator==(const Fruit& other){return *name == *other.name;};
    bool operator!=(const Fruit& other){return *name != *other.name;};
    friend std::istream & operator>>(std::istream& is, Fruit& readFruit);
};
#endif

如果您尝试打印readFruit.name ,它将显示垃圾值,直到找到一个空终止符,这就是我假设您说的25个字符“ 全部垃圾

这样分配内存:

readFruit.name = new char[tempString.length()+1];

for循环之后执行:

readFruit.name[i] ='\\0'; // C strings are null terminated

要解决您的问题,您需要对name字符数组进行空终止。 现在,您已经复制了所有字符,但是您需要在末尾有一个二进制零字符才能使所有字符串函数正常工作。 因此,您需要再分配一个字符,并为其写入'\\0'

就是说:使用std::string作为水果的名称。 没有必要通过保留字符数组来帮助自己解决大量的自制错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM