user821
user821

Reputation: 110

The same logic on an array is producing different results

This is the function:

void print(int arr[], int size)
{
    int* count = new int [size];
    for(int i = 0; i < size; i++){
    count[arr[i]]++;
    cout << count[arr[i]] << endl;
    }
}

When I call (in my main) print(arr, sizeof(a)/sizeof(a[0])) where a = {4, 2, 4, 5, 2, 3}, I would get the updated count of each number in the array. Now, let's say I want to do something very similar to this but in my int main():

int* my_arr = new int[10];
my_arr[1]++;
cout << "my_arr[1] = " << my_arr[1];

The last statement prints something like 15799121, which I assume is the memory address of my_arr[1]. How is this not the same in print()? Shouldn't cout << count[arr[i]] << endl; produce the same result?

Upvotes: 2

Views: 55

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

For default initialization,

otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

That means given new int [size], the elements of the array are initialized to indeterminate values, use of these values leads to UB, means anything is possible.

You might want value initialization, i.e. new int [size](); all the elements would be initialized to 0 exactly.

Upvotes: 4

Related Questions