c++中动态改变指针的大小
Dynamically Changing the Size of the Pointer in C++
我有以下结构
typedef struct DeviceInfo
{
char[30] name;
char[30] serial Number;
}DeviceInfo;
I am doing this
DeviceInfo* m_DeviceInfo = new DeviceInfo[4];
// Populate m_DeviceInfo
然后我想把m_DeviceInfo
的大小调整为6,并想保留
常规数组不能这样做。我建议您使用vector,它可以随着您添加更多元素而增长(因此您甚至不必指定初始大小)。
好的c++方法是使用合适的容器。显然,您应该使用std::vector容器,例如:
std::vector<DeviceInfo> m_DeviceInfo;
m_DeviceInfo.resize(4);
这需要对DeviceInfo进行一些约束。特别是,它应该有一个不带参数的构造函数,以及复制构造函数…
你的问题措辞很糟糕。你当然不会改变sizeof(DeviceInfo*)
,它在32位机器上可能是4个字节,在64位机器上可能是8个字节。
m_DeviceInfo
指向包含4个元素的DeviceInfo
数组。数组不能调整大小。相反,你应该删除并创建6个元素。
DeviceInfo * m_DeviceInfo2 = new DeviceInfo[6];
memcopy( m_DeviceInfo,m_DeviceInfo2, 4 );
delete[] m_DeviceInfo;
但是你应该使用向量
std::vector<DeviceInfo> m_DeviceInfo;
// or
std::vector<std::shared_ptr<DeviceInfo>> m_DeviceInfo;
调整大小
m_DeviceInfo.resize(m_DeviceInfo.size()+ 2);
你的问题有两个选择,这取决于你是否想使用STL。
typedef struct DeviceInfo
{
char[30] name;
char[30] serial Number;
} DeviceInfo;
与STL: //requires vector.h
vector<DeviceInfo> m_deviceInfo;
DeviceInfo dummy;
dummy.name = "dummyName";
dummy.serialNumber = "1234";
m_deviceInfo.insert(m_deviceInfo.begin(), dummy);
//add as many DeviceInfo instance you need the same way
或不带STL:
//implement this
DeviceInfo* reallocArray(DeviceInfo* arr, int curItemNum, int newItemNumber)
{
DeviceInfo* buf = new DeviceInfo[newItemNumber];
for(int i = 0; i < curItemNum; i++)
buf[i] = arr[i];
for(int i = curItemNum; i < newItemNumber; i++)
buf[i] = null;
}
//and in your main code
DeviceInfo m_DeviceInfo = new DeviceInfo[4];
m_DeviceInfo = reallocArray( m_DeviceInfo, 4, 6 );
1)新建一个大小合适的数组,并将旧数组中的所有元素复制到新数组中。
2)使用std::vector
(我的建议)
最好的解决方案是在程序中使用向量。
参考此网站http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#VECTOR
这个网站将帮助你解决你的问题。
这里可以推送数据。不用担心结构的大小
语法错误:
DeviceInfo m_DeviceInfo = new DeviceInfo[4];
应:DeviceInfo* m_DeviceInfo = new DeviceInfo[4];
一个更好的选择是使用std::vector
。
std::vector<DeviceInfo> vec;
//populate:
DeviceInfo inf;
vec.push_back(inf);
vec.push_back(inf);
//....
有几种方法可以做到这一点,但是应该使用c++中的realloc函数。它将重新分配连续内存,并将前一个内存的值复制到新内存中。例如:
temp_DevInfo = (DeviceInfo*) realloc (m_DeviceInfo, (2) * sizeof(struct DeviceInfo));
free(m_DeviceInfo);
m_deviceInfo = temp_DevInfo;
你执行2 * sizeof(DeviceInfo),因为你想再加2,加上之前的4是6。然后应该释放/删除前一个对象。最后将旧指针设置为指向刚刚分配的新对象。
这应该是它的要点
查看realloc的文档
- 通过从构造函数中的'this'复制的指针改变常量对象
- 当矢量改变容量时,有什么方法可以更新指针/参考值
- 更改指针指向的对象,但对象不会改变
- 改变指针的价值
- 函数更改后指针的显示值与数组 C 一起改变
- 为什么当我们反转此函数中的字符串时,char *str 的指针没有改变?
- 你能改变指针指向的大小吗?
- 为什么在const仍然是const的情况下改变了指向const的指针的差异?
- c++中动态改变指针的大小
- 两个指向相同值的指针,只改变其中一个——c++中的双链表
- c++指针:在不改变地址的情况下改变内容
- c++的new操作符保证返回的指针不会改变它的值吗?
- this指针在调用成员函数时改变
- 多线程 - 为什么在引用上工作不会改变它,而在指针上工作正常
- 在c++中,改变指针返回后指向的对象
- c++的共享指针向量.如果在vector外强制转换,它会改变vector中的指针吗?< / h1 >
- 如何使函数不改变指针形式的参数一旦完成
- 通过作为参数传递的指针改变int变量的值
- 指向unordered_map表项的指针改变了,但表项不变
- 构造函数指针改变