首页 > 解决方案 > 如何使用新的 C++ 创建动态数组?

问题描述

我正在尝试动态初始化一个整数数组,因为数组的大小会根据输入而变化。程序如下:

int main()
{
    int* list = createList("dis.bin");
    for (int i = 0; i < sizeof(list) / sizeof(int); i++)
    {
        printf("%d\n", list[i]);
    }
}

具有createList()编写的功能:

int* createList(const char* file_name)
{
    int counter = 1;
    int* inst{};
    FILE* myFile = fopen(file_name, "rb");
    if (myFile == nullptr)
    {
        printf("\nFile not opened\n");
        return 0;
    }

    int x = 0;
    for (int i = 0; !(feof(myFile)); i++)
    {
        fread(&x, sizeof(int), 1, myFile);
        inst = new int[counter];
        inst[i] = x;
        printf("%08x #%-4d |   Int equiv: %-12d |   Bin equiv: %s\n", x, counter, inst[i], ToBinary(inst[i], 0));
        counter += 1;
        x = 0;
    }

    return inst;
}

createList从文件中读取.bin(基本上包含一个字节数组)并将每对 4 个字节插入到数组中的一个项目中inst。我通过根据counter变量为数组分配新的空间来做到这一点。(所以无论值计数器变成数组的大小inst = new int[counter])然后我将给定索引处的数组内容设置为i等于 x(读取的字节对)我会假设它createList至少可以正常工作,因为printf打印每个元素的语句inst[]

但是,当我调用createList("dis.bin")main 并将其分配给变量int* list时,我尝试遍历每个值。但这只是打印出一个未初始化的值(-842150451,如果你好奇的话)。所以我不确定我在这里做错了什么?

我应该提到我没有使用向量或任何标准容器。我只是在处理数组。我也printf出于特定原因使用。

标签: c++new-operatordynamic-arrays

解决方案


这个问题被标记为 C++,但是 OP 正在显示 C 代码并说他们需要在 C 中使用它,所以我将在 C 中显示它......但前提是它使用new而不是malloc

int* createList(const char* file_name, int& count)
{
    // initialize count, so that way if we return early, we don't have invalid information
    count = 0;

    // open the file ad "READ" and "BINARY"
    FILE* myFile = fopen(file_name, "rb");
    if (!myFile)
    {
        printf("\nFile not opened\n");
        return 0;
    }

    // calculate how many 4-byte integers exist in the file using
    // the file length
    fseek(myFile, 0, SEEK_END);
    count = ftell(myFile) / sizeof(int);
    rewind(myFile);
    
    // allocate the memory
    int* returnData = new int[count];

    // read in 4-byte chunks to our array until it can't read anymore
    int i = 0;
    while (fread(&returnData[i++], sizeof(int), 1, myFile) == 1);

    // close the file
    fclose(myFile);

    // return our newly allocated data
    return returnData;
}

int main()
{
    int count;
    int* myInts = createList("c:\\users\\andy\\desktop\\dis.bin", count);
    for (int i = 0; i < count; ++i) {
        printf("%d\n", myInts[i]);
    }
    // don't forget to delete your data. (another reason a vector would be better suited... no one remembers to delete :)
    delete myInts;
}

推荐阅读