简体   繁体   中英

Why is my empty array not empty?

I write the following code and set a breakpoint in xcode:

#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
    int array[12];
    return 0;        //Set breakpoint here
}

在此输入图像描述

The debugger panel shows the first 6 elements contain non zero int s. Why is this?

int array[12];

This declares an array with 12 elements, not an empty array.

Furthermore it declares them without an initializer, which (in function scope) means that they will be default initialized. For int that means no initialization is performed and the resulting int s will have indeterminate values. This behavior is defined in the specification for C++.

If you want to zero initialize the array then you need to give it an initializer:

int array[12] = {};

The reason that this is not forced behavior is that there is a performance cost to initialization and some programs are written to work correctly without needing to suffer that penalty.

Because you only declared the array, not initialized it.

When you declare the only thing that happens is that you reserve a certain area of memory. What is already stored on that area can be anything left over from other operations/programs.

Only global and static variables (incl. arrays) are assured to have zero initial values. For local arrays (as in your code) you can initialize to zeroes using:

int array[12] = {0};

Check this link for more details: How to initialize array to 0 in C?

除非你告诉它,否则C ++编译器不会初始化变量。

Because your array is not initialized . Debugger panel is showing you the previous value stored at that locations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM