3

I'm playing around with arrays in C++. I defined a 2d array called matrix and am going to extract the negative values and assign it to the array called array.

Is there a way to initialize an array to zero quickly rather than enumerating all the elements? I looked through other postings and lines such as: int array[10] = {} or int array[10] = {0} do not work on my compiler. I get the error message error: variable-sized object ‘array’ may not be initialized if I try using those statements.

My text book said that all arrays are initialized to zero when declared, but I tested this on my compiler and this was not true; I had to force it to zero by using a for-loop. Is there a correct way of doing this?

Oh by the way, I have a mac and use g++ to compile. When I do man g++ it says its a symbolic link to llvm-gcc compiler.

#include<iostream>

const int NROWS = 4, NCOLS = 5;
int matrix[][NCOLS] = {    16,  22,  99,  4, 18, 
                         -258,   4, 101,  5, 98, 
                          105,   6,  15,  2, 45, 
                           33,  88,  72, 16, 3};

int main()
{
    int SIZE = 10;
    int array[SIZE];
    int count=0;

    // Values of array before initalized    
    for(int i = 0; i < SIZE; i++)
    {
        std::cout << array[i] << " ";
    }    
    std::cout << std::endl;

    //Initialize array to zero
    for(int i = 0; i < SIZE; i++)
    {
        array[i]=0;
        std::cout << array[i] << " ";
    }    
    std::cout << std::endl;

    // Extract negative numbers and assign to array
    for(int i = 0; i < NROWS; i++)
    {
        for(int j = 0; j < NCOLS; j++)
        {
            printf("matrix[%i,%i]=%5i\n",i,j,matrix[i][j]);

            if(matrix[i][j] < 0)
            {
                array[count] = matrix[i][j];
                printf("\tarray[%d]= %4d",count, matrix[i][j]);
                printf("\tcount=%d\n", count);
                count++;                
            }
        }

    }

    // Values of array
    for(int i = 0; i < SIZE; i++)
    {
        std::cout << array[i] << " ";
    }

    std::cout << std::endl;

    return 0;
}
Kara
  • 6,115
  • 16
  • 50
  • 57
user1527227
  • 2,068
  • 5
  • 25
  • 36
  • *Must* it be an array? – ChiefTwoPencils Nov 08 '13 at 21:22
  • 'My text book said that all arrays are initialized to zero when declared', throw away that text book then. A text book should also have told you that `int SIZE = 10; int array[SIZE];` is not legal C++. You can't always rely on your compiler to tell you the difference between legal and illegal C++, you need a good text book. – john Nov 08 '13 at 21:23
  • Where do you go to find out nuances about compilers to see if declarations or initializations of variables or arrays are set to zero? – user1527227 Nov 08 '13 at 21:31

5 Answers5

6

I'm taking a guess here.

int array[10] = {0};

is perfectly legal and should work on any compiler, but I think you tried

int SIZE = 10;
int array[SIZE] = {0};

which is entirely different, and not legal. Array bounds must be constants, not variables.

Some compilers accept variable bounds, but that doesn't make it legal.

john
  • 85,011
  • 4
  • 57
  • 81
  • Ah I see. I have to do `const int SIZE = 10;`. That is why I was getting that error message. SIZE must be declared as a constant for that to work. – user1527227 Nov 08 '13 at 21:28
3

Change int SIZE = 10; to const int SIZE=10; or enum{SIZE=10};, and your {} based initialization should work.

You have accidentally used a gcc extension allowing for variable sized arrays.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
1

What you need to do is up at the top where you have:

int array[SIZE];

replace it with:

int array[SIZE] = {};

if you were trying to do:

array[SIZE] = {}; 

later on, it wouldn't work the same. in that case, it would fail (accessing [10] when there's only [0]-[9]).

You could also use a static array.

See:

How to initialize all members of an array to the same value?

Or if you want to use the STL Array type,, you can look at:

http://www.cplusplus.com/reference/array/array/?kw=array

you might even need to just make the SIZE var const.

Community
  • 1
  • 1
Plasmarob
  • 1,321
  • 12
  • 20
  • Thanks guys, it appears I was forgetting to declare SIZE as a constant. Must do `const int SIZE` for this to work!! – user1527227 Nov 08 '13 at 21:29
1

This should work, and will zero-initialize the 9 remaining elements.

int array[10] = {0};

See: Array initialization in C++

Community
  • 1
  • 1
varcharmander
  • 238
  • 1
  • 11
0

If array size is variable-dependent you must: loop through or

int array[x];

memset(array, 0, x);

If array size is hardcoded you can:

int array[10] = {0};

Community
  • 1
  • 1
Scony
  • 4,068
  • 1
  • 16
  • 23
  • Incorrect! This should be `memset(array, 0, sizeof(array[0]) * x)` or simpler: `memset(array, 0, sizeof(array))`. The `num` argument of memset is in **bytes**. – Benno Straub Dec 03 '21 at 17:23