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.