Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to initialize two-dimensional array in C language
How to initialize two-dimensional array in C language
1 There are two methods.

(1) can be initialized by direct assignment at definition time.

(2) Once defined, you can assign values to its elements one by one.

Two examples

# include & ltstdio.h & gt

Invalid? Display (int? arr[2][3],? int? Row,? int? col){

For what? (int? Me? =? 0; ? Me? & lt? Row; ? i++){

For what? (int? j? =? 0; ? j? & lt? col? j++){

printf("%d?" ,? arr[I][j]);

}

puts(" ");

}

puts(" ");

}

int? main(){

//method (1)

int? arr 1[2][3]? =? {? {? 1,? 2,? 3? },? {? 4,? 5,? 6? }? };

//Method (2)

int? arr 2[2][3];

int? num? =? 1;

For what? (int? Me? =? 0; ? Me? & lt? 2; ? i++){

For what? (int? j? =? 0; ? j? & lt? 3; ? j++){

arr2[i][j]? =? num++;

}

}

Display (arr 1,? 2,? 3);

Display (arr2, 2,? 3);

getchar();

Return? 0;

}3 running results

It can be seen from the results that the two methods have achieved the same effect.

4 expansion

Because the addresses of elements in the array in C language are continuous, the following writing method is also possible, and the running effect is the same as above.

# include & ltstdio.h & gt

Invalid? Display (int? arr[2][3],? int? Row,? int? col){

For what? (int? Me? =? 0; ? Me? & lt? Row * column; ? i++){

For what? (int? j? =? 0; ? j? & lt? col? j++){

printf("%d?" ,? arr[I][j]);

}

puts(" ");

}

puts(" ");

}

int? main(){

//method (1)

int? arr 1[2][3]? =? {? 1,? 2,? 3,? 4,? 5,? 6? };

//Method (2)

int? arr 2[2][3];

int? num? =? 1;

int? *p? =? * arr2// points to the first element of the array.

For what? (int? Me? =? 0; ? Me? & lt? 2? *? 3; ? i++){

*p++? =? num++;

}

Display (arr 1,? 2,? 3);

Display (arr2, 2,? 3);

getchar();

Return? 0;

}