Re-initialize array into another value


I have an array declared:
int hours[4] = {1,2,3,4}

now I am building another array

int array[count];
array[0] = 5;
array[1] = 6;
array[2] = 7;

now how do I set hours = arr
I mean hours should have values {5,6,7} only

You’d need to copy the data from one to the other.
You can always use a loop to iterate over the individual entries but if you are absolutely sure that both arrays are compatible you could also use memcpy() (limited to the size of the smaller array tho’).

both arrays are of different size,
I tried memcpy(hours, array, sizeof array);
but it keeps the 4th element as it is

What else would you expect?

I expect its value reset to some unexpected value e.g. -1
e.g. {5,6,7,-1}

Why not 0 or (2^31-1) - how should the code know what value you assume to be the value of a non-initialised or “unexpected” integer?

You already implied the ambiguity of your expectation when you used "e.g." as this indicates only one of multiple possibilites but computers don’t usually guess what you might mean.

actually I am saving hours in the array,
so if I use 0 then it will consider it 0hrs
that is why I need value other than 0

some high value is also OK

Do you think a computer has any idea or interest of what you called your variable in code or what you intend to store therein?
When the code is compiled none of the variable names ever make it into the binary.

If you want all fields to be populated you need to do so and not leave anything to chance.
As I said you can always iterate over all the fields and provide any alternative/default value for fields not provided - but you need explicitly state which.
You could also first reset the entire field via memset(hours, 0xFF, sizeof(hours)) before copying in the under-determined array.
Or you can create a class with a copy operator to get the job done.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.