英文:
The same logic on an array is producing different results
问题
以下是翻译好的部分:
这是该函数:
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;
}
}
当我在主函数中调用时,print(arr, sizeof(a)/sizeof(a[0]))
,其中a = {4, 2, 4, 5, 2, 3}
,我将获得数组中每个数字的更新计数。
现在,假设我想在我的int main()
函数中做类似的事情:
int* my_arr = new int[10];
my_arr[1]++;
cout << "my_arr[1] = " << my_arr[1];
最后一条语句会打印类似于15799121的内容,我认为这是my_arr[1]
的内存地址。为什么在print()
函数中不是这样呢?难道cout << count[arr[i]] << endl;
不应该产生相同的结果吗?
希望这有所帮助。如果您有其他问题,请随时提出。
英文:
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?
答案1
得分: 4
对于默认初始化,
否则,什么都不会发生:具有自动存储期的对象(及其子对象)将被初始化为不定值。
这意味着给定new int [size]
,数组的元素将被初始化为不定值,使用这些值会导致UB,意味着任何情况都有可能发生。
你可能希望使用值初始化,即new int [size]()
;所有元素将被初始化为0
。
英文:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论