在一个数组上相同的逻辑产生了不同的结果。

huangapple go评论73阅读模式
英文:

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 &lt; size; i++){
	count[arr[i]]++;
	cout &lt;&lt; count[arr[i]] &lt;&lt; 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 &lt;&lt; &quot;my_arr[1] = &quot; &lt;&lt; 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 &lt;&lt; count[arr[i]] &lt;&lt; endl; produce the same result?

答案1

得分: 4

对于默认初始化

否则,什么都不会发生:具有自动存储期的对象(及其子对象)将被初始化为不定值。

这意味着给定new int [size],数组的元素将被初始化为不定值,使用这些值会导致UB,意味着任何情况都有可能发生。

你可能希望使用值初始化,即new int [size]();所有元素将被初始化为0

英文:

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.

huangapple
  • 本文由 发表于 2020年1月7日 00:07:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定