Array set to zero?

I am trying to set all the values within my array to zero, for some reason the last row of the array will not set to zero.

Any ideas?

#include <iostream>
int main ()
{
int data[200][4]={};
for(int i =1;i<=200;i++){std::cout<<"row number is..."<<i<<"\t"<<data[i][1]<<"\t"<<data[i][2]<<"\t"<<data[i][3]<<"\t"<<data[i][4]<<std::endl;}
return 0;
}
1
2
3
4
5
6
7
8
#include <iostream>
int main ()
{
    int data[200][4]={{0}};
    for(int i =0;i<200;i++)
        std::cout<<"row number is..."<<i<<"\t"<<data[i][0]<<"\t"<<data[i][1]<<"\t"<<data[i][2]<<"\t"<<data[i][3]<<std::endl;
    return 0; 
}


0 to 199, not 1 to 200 in the for loop.
Last edited on
Array starts from 0 not from 1. So you go set values from i = 0 to i = 199.
But now you live data[0][0] without value, and try to add value to data[200][0] that does not exist
Last edited on
You already initialized all elements of the array to zero

int data[200][4]={};

So there is no need to do the same in the loop except that you want to learn loops.
use memset :)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;


int main()
{
	int v[10];

	/*init v seting 0 in each position of array*/
	memset(v, 0, sizeof(v)); //clear buffer

	/*Display content of v*/
	for(int i=0; i<(sizeof(v)/sizeof(int)); i++)
		cout<<v[i]<<endl;
	/*w8 for user to press key to exit*/
	cin.get();
	cin.get();
	return 0;
}



documentation : http://www.cplusplus.com/reference/clibrary/cstring/memset/
Last edited on
closed account (zb0S216C)
@gtkano: -1 for suggesting an unsafe function. Note that a call to "memset( )" after a declaration context is not initialisation. The better alternative here is "std::vector":

 
std::vector<int> array(200, 0); // Add 200 ints with the value of 0 

Wazzal
Last edited on
TY Framework for pointing that out .
Now I know that unsafe function exist :). Now I need to find out more info about them.
@gtkano
TY Framework for pointing that out .
Now I know that unsafe


By the way some compilers do use memset for local declarations as in the original code

int data[200][4]={};
Topic archived. No new replies allowed.