【发布时间】:2017-06-10 22:43:48
【问题描述】:
我刚刚开始使用 C++,但我无法理解我的代码是如何工作的:
好的,我分配了内存,但是在分配的时候没有人知道要分配的内存的大小。但代码仍然有效。 分配了多少内存?编译器如何知道我需要多少内存?
编辑:
对不起,如果我的问题不清楚。让我试着澄清一下。所以我使用我的指针在堆中动态分配一些内存。但由于 sting 变量中没有文本,我认为很难知道我将通过 getline 输入多少文本(字节)。
我尝试询问两种不同文本文字的大小,是的,它们的大小不同。
sizeof("") // is 1 (because of the ending 0 maybe?)
sizeof("sometext") // is 9
但是对于字符串:sizeof 两次都给了我 4。很明显 sizeof() 给了我指向字符串的指针的长度。
如何分配内存?如果我为一个新字符串分配内存,只分配一个指向字符串中第一个字符的内存地址的指针? 显然我输入的字符必须存储在某个地方。我首先分配内存,然后将一些文本加载到其中。
编辑 2:使编辑后的代码看起来像代码,而不是纯文本。
//Edit:
string a,b = "sometext";
cout << sizeof(a) << endl; //4
cout << sizeof(b); //4
//--------------------------------------------------------
#include <iostream>
#include <string>
#include <exception>
using namespace std;
int main()
{
//Defining struct
struct musicCD
{
string artist, title; // artist of the CD
};
//Memory allocation
musicCD *ptr;
try{ptr = new musicCD;}
catch(bad_alloc){cerr << "Out of memory :(";return -1;}
catch(...){cerr << "Something bad happened :O !";return -1;
}
//Get the data to store:
cout << "Please enter the data for the CD!' " << endl;
cout << "Please enter the artist: ";getline(cin, ptr->artist); cout << endl;
//Write out the data
cout << "The data entered: " << endl;
cout << "The artist performing is: \t" << ptr->artist << endl;
delete ptr;
return 0;
}
【问题讨论】:
-
是什么让你相信“没有人知道要分配的内存大小”?这很明显。
musicCd对象的一个实例需要足够的内存,它被分配,然后被释放。 -
没有人知道要分配的内存大小 不正确。
musicCD具有固定大小(使用sizeof查看其大小)。 -
我不相信标准在意,但是musicCD的大小是由new决定的,您可以通过标准操作来获取大小,即
sizeof(musicCD) -
附带说明,IDE 并不关心将/不会分配多少内存。另一方面,编译器会。这不是问题的真正主题,而是可能导致以后理解问题的错误。
-
@op 我认为等式中缺少的部分是 sizeof(string) 是恒定的。如果将内容添加到字符串,则新内容将在堆上进行管理。这意味着字符串 s("") 和字符串 t("ssjlskjskljlsj") 在堆栈上的大小相同;
标签: c++ memory memory-management