if i define num[a][b] variable as global like below , each array element's value is '0' .However , if I define it locally (in the pr_row function),each elements value is randomly appointed.Why ?
if any help appreciated ,
int num[10][10];
void pr_row(int j);
int main(void)
{
pr_row(5);
return 0 ;
}
// a[j][k] is equivalent to *((base-type *)a+(j*row length)+k) //
void pr_row(int j)
{
int *p, t;
p = (int *) &num[j][0]; /* get address of first
element in row j */
for(t=0; t<10; ++t) cout<< *(p+t) << endl;
}
if i define num[a][b] variable as global like below , each array element's value is '0' .However , if I define it locally (in the pr_row function),each elements value is randomly appointed.Why ?
Because that's the way the language designers decided it should be.
#include <iostream>
#include <cstring> // for memset
usingnamespace std;
int main(void)
{
constint rows = 3;
constint cols = 4;
// approach 1
int num[rows][cols] = {0};
// in C++ (but not C), you can also use empty braces
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < cols; ++j) {
cout << " " << num[i][j];
}
cout << endl;
}
// approach 2
int another[10][10];
memset(another, 0, sizeof(another));
// this can also be used to reset an array to zero
// approach 3 is to use a loop/loops to set the elements
// to zero one by one (no code...)
return 0 ;
}
The second and third approaches are pretty obvious!?
The first relies on another language feature. If you set some but not all elements of an array, the rest are automatically zeroed. So you could also use
int num[10][10] = {1};
if you want element to set num[0][0] = 1 and all the other elements to 0
or even
int num[rows][cols] = {{1}, {2}, {3}};
to set the first element of each row to 1, 2, 3 but all other elems to 0 (for a 3 x n array.)
if the array is defined locally, the values aren't appointed at all, so if you access them, you can see whatever has been in the memory before.
If the array is globally defined, they are intialized, because it is required by the standard (don't ask (at least me) why).
PS: what exactly are you doing? if you are using c++ you should go for std::array or std::vector.
and if you want to stick to c-style arrays, your pr_row function could also be written differently, because right now it is (at least for me) a bit confusing. something like
1 2 3 4
void pr_row( int i )
{
for ( int j = 0; j < 10; ++j ) cout << num[i][j] << endl;
}
this is clearer in my eyes.
and also some people might say that global variables aren't good style