c++中动态改变指针的大小

Dynamically Changing the Size of the Pointer in C++

本文关键字:指针 改变 动态 c++      更新时间:2023-10-16

我有以下结构

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的文档