创建动态分配的数组C

Create Dynamically Allocated Array C++

本文关键字:数组 动态分配 创建      更新时间:2023-10-16

我正在尝试创建C 中unsigned char*类型的动态分配数组。但是,当我这样做时,我会恢复一个字符串,而不是封闭的括号( {}(数组,这是我想要的。

unsigned char* arr = new unsigned char[arrLen];

代码图片

图片显示了两个

之间的区别

您看到后者不仅在第一个角色之后什么都不走?那就是我想要的。

我将如何解决这个问题?

谢谢您的时间。

首先,de Debugger默认假定char代表ASCII字符,而不是数字。它将显示为char

arr2具有类型const char[3],因此调试器知道有3个要素可以显示。

arr具有const char*类型。调试器不知道它是一个元素还是一个具有一定数量元素的数组。

例如,如果您使用的是Visual Studio,则可以通过在手表菜单中使用语法arr,3添加"可变手表"来提示调试器显示三个字符。

我不确定这是否是您想要的,但是您是否尝试过使用std :: vector?它至少可以处理您要寻找的动态分配,并且不应将null字符视为字符串的末端。

 #include <vector>
 std::vector<char> arr = { 0x5A, 0x00, 0x2B };

如果要动态生长的chars(array(列表,您需要的是一个指针列表,其中每个段的列表是一个大数字1000。班级牺牲了成长能力的记忆使用。

矢量容器类允许动态增长,但使用大量内存

此外,动态增长一次不建议用于大量数据列表。如果您想为大列表的动态增长,请在诸如以下内容之类的块中创建一个列表。使用一个大的列表段 - 说1000个单位。我在以下示例中创建了1000个列表。我通过创建1000个指针的阵列来做到这一点。这将创建您要寻找的100万个炭,并可以动态发展。以下示例显示了您将如何执行此操作。

.
void main() {
    unsigned char* listsegment[1000];
int chrn=0;
    int x, y = 0;
    for (int x = 0; x < 1000; x++) {
        listsegment[x] = new unsigned char[1000];
        for (y = 0; y < 1000; y++) {
            *(listsegment[x] + y) = chrn;
if (chrn >=255) chrn=0;
else chrn++;
        }
    }
}

完成程序 - 如果需要动态分配超过1000个段?

然后创建一个段集列表。它可以在链接列表中,也可以在容器类中。

由于单个集合创建了1000个字符的1000个片段,因此这些集合的集合可能不大于1000。一千组将等于(1000*1000(*1000,这将等于10亿。因此,该集合只需要1000或以下,可以快速迭代 - 这使得无需随机访问该集合。

这是通过无限大量集合组合支持无限量集的程序。这也是一个很好的示例,它通常是分割的动态内存分配。

#include <iostream>
#include<queue>
using namespace std;
struct listSegmentSetType {
    unsigned char* listSegment[1000];
    int count=0;
};

void main() {
    listSegmentSetType listSegmentSet;
    queue<listSegmentSetType> listSegmentSetCollection;
    int numberOfListSegmentSets = 0;
    int chrn = 0;
    int x, y = 0;
    listSegmentSet.count = 0;
    for (int x = 0; x < 1000; x++) {
        listSegmentSet.listSegment[x] = new unsigned char[1000];
        for (y = 0; y < 1000; y++) {
            *(listSegmentSet.listSegment[x] + y) = chrn;
            if (chrn >= 255) chrn = 0;
            else chrn++;
        }
        listSegmentSet.count++;
    }
    // add just completely filled out first list segment set to que
    listSegmentSetCollection.push(listSegmentSet);
    numberOfListSegmentSets++;
    // now fill in second set of list segments-
    listSegmentSet.count = 0;
    for (int x = 0; x < 1000; x++) {
            listSegmentSet.listSegment[x] = new unsigned char[1000];
        for (y = 0; y < 1000; y++) {
            *(listSegmentSet.listSegment[x] + y) = chrn;
            if (chrn >= 255) chrn = 0;
            else chrn++;
        }
        listSegmentSet.count++;
    }
    listSegmentSetCollection.push(listSegmentSet);
    numberOfListSegmentSets++;
    // now fill out any more sets of list segments and add to collection 
    // only when count listSegmentSet.count is no
    // longer less than 1000.  
}