用C ++动态改变指针的大小

问题描述 投票:0回答:8

我有以下结构

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,并希望保留前4值。

怎么用c ++做?

c++ struct new-operator dynamic-allocation
8个回答
6
投票

你不能用常规数组做到这一点。我建议你使用vector,它可以随着你添加更多元素而增长(所以你甚至不需要指定初始大小)。


3
投票

好的C ++方法是使用适当的容器。显然,你应该使用std::vector容器,例如:

std::vector<DeviceInfo> m_DeviceInfo;
m_DeviceInfo.resize(4);

这需要对DeviceInfo进行一些约束。特别是,它应该有一个没有参数的构造函数,以及复制构造函数......

你的问题很严厉。你肯定不会改变在32位机器上可能是4个字节的sizeof(DeviceInfo*),在64位机器上改变8个字节。


3
投票

您的问题有两个选项,这取决于您是否要使用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 );

3
投票

1)创建一个适合的新数组,并将旧数组的所有元素复制到新数组中。

2)使用std::vector(我的推荐)。


2
投票

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);

2
投票

最好的解决方案是在程序中使用vector。

请参阅此网站http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#VECTOR

该网站将帮助您解决问题。

在这里你可以推送数据。不需要打扰结构的大小。


1
投票

你的语法错了:

DeviceInfo m_DeviceInfo = new DeviceInfo[4];

应该:

DeviceInfo* m_DeviceInfo = new DeviceInfo[4];

A better alternative would be the use of std::vector.

std::vector<DeviceInfo> vec;

//populate:
DeviceInfo inf;
vec.push_back(inf);
vec.push_back(inf);
//....

0
投票

好吧有几种方法可以做到这一点,但你应该在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的文档。

© www.soinside.com 2019 - 2024. All rights reserved.