簡體   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