New 在每次迭代中分配相同的内存
New allocates the same memory with each iteration
我正在尝试构建一个类似列表的 C 字符串堆存储。
这是程序的简化部分。
但是,每次迭代 new
都会出现相同的地址。
#include <iostream>
class listStringContainer {
public:
listStringContainer(const char* c);//constructor
};
int main(){
listStringContainer lsc1 ("Lorem ipsum");// calling the constructor
}
listStringContainer::listStringContainer(const char* c) {//constructor
char * Memory_Address;
auto time{5};
while (--time>=0) {
Memory_Address = new char[16];
//the memory location is to be saved into a vector
std::cout << "Memory_Address: "<< &Memory_Address << std::endl;
}
}
输出:
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
在 g++ 和 MSVS 上的结果相同。
为什么new
指定同一个地址,如何让新的指定不同地址?
您需要转换 static_cast<void*>(Memory_Address)
以获取存储在 Memory_Address
中的值。
让我们考虑一下:
char * p;
p= new char[16];
strcpy(p, "Hello");
cout << *p << endl; // Prints 'H'
cout << &p << endl; // Prints address of p
cout << p << endl; // Prints "Hello"
cout << static_cast<void*>(p) << endl; // Prints address of p[0]
考虑以下相同的场景,但数据类型为整数:
int * ptr;
ptr= new int[16];
ptr[0] = 10;
cout << *ptr << endl; // Prints 10
cout << &ptr << endl; // Prints ptr address
cout << ptr << endl; // Prints address of ptr[0]
因此,Integer 不需要转换为 void*
来获得 &ptr[0]
我正在尝试构建一个类似列表的 C 字符串堆存储。 这是程序的简化部分。
但是,每次迭代 new
都会出现相同的地址。
#include <iostream>
class listStringContainer {
public:
listStringContainer(const char* c);//constructor
};
int main(){
listStringContainer lsc1 ("Lorem ipsum");// calling the constructor
}
listStringContainer::listStringContainer(const char* c) {//constructor
char * Memory_Address;
auto time{5};
while (--time>=0) {
Memory_Address = new char[16];
//the memory location is to be saved into a vector
std::cout << "Memory_Address: "<< &Memory_Address << std::endl;
}
}
输出:
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
在 g++ 和 MSVS 上的结果相同。
为什么new
指定同一个地址,如何让新的指定不同地址?
您需要转换 static_cast<void*>(Memory_Address)
以获取存储在 Memory_Address
中的值。
让我们考虑一下:
char * p;
p= new char[16];
strcpy(p, "Hello");
cout << *p << endl; // Prints 'H'
cout << &p << endl; // Prints address of p
cout << p << endl; // Prints "Hello"
cout << static_cast<void*>(p) << endl; // Prints address of p[0]
考虑以下相同的场景,但数据类型为整数:
int * ptr;
ptr= new int[16];
ptr[0] = 10;
cout << *ptr << endl; // Prints 10
cout << &ptr << endl; // Prints ptr address
cout << ptr << endl; // Prints address of ptr[0]
因此,Integer 不需要转换为 void*
来获得 &ptr[0]