[英]Copy data from one matrix to another in C
I have two matrix dynamically allocated.I want to copy all the data from the first matrix and center it by a border to the second one.Here is my code which apparently does not work properly so I would be grateful for some help: 我有两个动态分配的矩阵,我想将第一个矩阵中的所有数据复制并通过边框将其居中到第二个矩阵中,这是我的代码,显然不能正常工作,所以我将不胜感激:
The first matrix: 第一个矩阵:
unsigned char ** sudo=(unsigned char **) malloc (width*sizeof (unsigned char*));
if ( sudo != NULL){
for (k=0; k<width ;k++){
sudo[k] =(unsigned char*) calloc (height,sizeof (unsigned char));
}
}
The second one: 第二个:
unsigned char ** fmatr=(unsigned char **) malloc ((width+border)*sizeof (unsigned char*));
if ( fmatr != NULL){
for (k=0; k<(width+border) ;k++){
fmatr[k] =(unsigned char*) calloc ((height+border),sizeof (unsigned char));
}
}
How I center first matrix in the middle of the second one: 我如何在第二个矩阵的中间居中放置第一个矩阵:
for(i=0,k=0;i<(width+border);i++,k++){
for(j=0,l=0;j<(height+border);j++,l++){
if((i>(2*border)) && (j>(2*border))){
fmatr[i][j]=sudo[k][l];
}
}
}
Any ideas? 有任何想法吗?
Since the first matrix has width x height entries, you want to loop from 0 to width-1 (not width-1+border) and from 0 to height-1 (not height-1+border). 由于第一个矩阵具有width x height条目,因此您要从0到width-1(不是width-1 + border)和从0到height-1(不是height-1 + border)循环。 Similarly, you want to add border/2
to the index of the second array when assigning. 同样,您要在分配时将border/2
添加到第二个数组的索引中。
for(i=0;i<width;i++){
for(j=0;j<height;j++){
fmatr[i+(border/2)][j+(border/2)]=sudo[i][j];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.