二维数组的学习
二维数组的拷贝
这里介绍两种拷贝的方式:
- 一种是通过指针的方式进行拷贝,另外一种是通过一维数组的方式进行拷贝。
- copy_arr函数实现的是指针方式的拷贝,copy_arr1实现的是一维数组方式的拷贝。两种拷贝的运行结果一样
//
//2023/6/28.
//
#include <stdio.h>
#define ROW 3
#define COLUMN 4
void copy_arr(double (*target)[],double (*source)[]);
void copy_arr1(double target[][COLUMN],double source[][COLUMN],int n);
void cop_arr1_1(double t[],double s[],int n);
int main(void){
double source[ROW][COLUMN] ={{100,2,3,101},{4,9,3,0},{7,3,5,4}};
double target[ROW][COLUMN];
double target2[ROW][COLUMN];
// copy_arr(target,source);
copy_arr1(target2,source,ROW);
for(int i=0;i<ROW;i++){
for(int j=0;j<COLUMN;j++){
printf("%.1f ",target2[i][j]);
}
}
return 0;
}
void copy_arr(double (*target)[COLUMN],double (*source)[COLUMN]){
for(int i=0;i<ROW;i++){
for(int j=0;j<COLUMN;j++){
*(*(target+i)+j) = *(*(source+i)+j);
}
}
}
void copy_arr1(double target[][COLUMN],double source[][COLUMN],int n){
for(int i=0;i<n;i++){
cop_arr1_1(target[i],source[i],COLUMN);
}
}
void cop_arr1_1(double t[],double s[],int n){
for(int i=0;i<n;i++){
t[i]=s[i];
}
}
变长数组函数调用时的定义
在C语言中,变长数组(Variable Length Arrays,简称VLA)是指在程序运行时动态定义长度的数组。与普通的静态数组不同,其长度可以在运行时根据需要进行分配和修改。
int main(void){
int m=3;
int n=5;
double source[ROW][COLUMN] ={{100,2,3,101,45},{40,9,3,0,20},{7,3,5,4,85}};
double target[m][n];
copy_arr(m,n,target,source);
print_sort(source);
printf("\n");
print_sort(target);
return 0;
}
/**变长数组定义的时候,m,n要定义在前面
* @param m
* @param n
* @param target
* @param source
*/
void copy_arr(int m,int n,double target[m][n],double source[][COLUMN]){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
target[i][j] =source[i][j];
}
}
}

浙公网安备 33010602011771号