Search code examples
c++new-operatordynamic-arrays

How to create a dynamic array using new C++?


I'm trying to initialize an array of integers dynamically, since the size of the array changes based on input. The program is as follows:

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

With createList() function as written:

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 reads from a .bin file (basically containing an array of bytes) and inserts each pair of 4 bytes to an item in the array inst. I do this by allocating a new amount of space for the array based on the counter variable. (So whatever value counter is becomes the size of the array with inst = new int[counter]) Then I set the contents of the array at the given index i equal to x (the pair of bytes read) I would assume it is working correctly in createList at least, because of the printf statement which is printing each element in inst[].

However, when I call createList("dis.bin") in main and assign it to the variable int* list, I try to iterate through each value. But this just prints out one uninitialized value (-842150451, if you're curious). So I'm not sure what I'm doing wrong here?

I should mention that I am NOT using vectors or really any std container. I am just working with arrays. I also am using printf for specific reasons.


Solution

  • This question is tagged as C++, but OP is showing C code and says they need it in C, so I will show this in C... but the pre-req is that it uses new and not 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;
    }