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; }
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.