如何在C中复制矩阵? [英] How to copy matrix in C?
本文介绍了如何在C中复制矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写应复制矩阵的函数matricopy,但编译器会抱怨:
I'm trying to write the function matricopy that should copy a matrix but the compiler complains:
/* minmatrix.c - test rows and columns of a matrix
* Copyright abandoned. This file is in the public domain. */
#include <stdio.h>
#define ROWCOUNT (3)
#define COLUMNCOUNT (4)
int imat[ ROWCOUNT ][ COLUMNCOUNT ];
char cmat[ ROWCOUNT ][ COLUMNCOUNT ];
double dmat[ ROWCOUNT ][ COLUMNCOUNT ];
int rmat[ ROWCOUNT ][ COLUMNCOUNT ];
void matriscopy (int * destmat, int * srcmat, int rowcount, int columncount)
{
int i, j;
for (i=0; i<rowcount; i=i+1) /* rad-nr */
for (j=0; j<columncount; j=j+1) /* kolumn-nr */
destmat[i][j] = srcmat[i][j];
}
int main()
{
int i; int j;
int * ip; char * cp; double * dp;
for( i = 0; i < ROWCOUNT; i = i + 1 )
for( j = 0; j < COLUMNCOUNT; j = j + 1 )
{
imat[ i ][ j ] = 10000 + 100*i + j;
cmat[ i ][ j ] = 10*i + j;
dmat[ i ][ j ] = 1.0 + i/100.0 + j/10000.0;
rmat[ i ][ j ] = 0;
};
printf( "\n Examining imat:\n" );
for( ip = &imat[ 0 ][ 0 ];
ip <= &imat[ ROWCOUNT - 1 ][ COLUMNCOUNT - 1 ];
ip = ip + 1 )
printf( "memory at: %lx contains value: %d\n", (unsigned long) ip, *ip );
printf( "\n Examining cmat:\n" );
for( cp = &cmat[ 0 ][ 0 ];
cp <= &cmat[ ROWCOUNT - 1 ][ COLUMNCOUNT - 1 ];
cp = cp + 1 )
printf( "memory at: %lx contains value: %d\n", (unsigned long) cp, *cp );
printf( "\n Examining dmat:\n" );
for( dp = &dmat[ 0 ][ 0 ];
dp <= &dmat[ ROWCOUNT - 1 ][ COLUMNCOUNT - 1 ];
dp = dp + 1 )
printf( "memory at: %lx contains value: %f\n", (unsigned long) dp, *dp );
/* Add a statement here to call your matriscopy function. */
printf( "\n Examining rmat:\n" );
for( ip = &rmat[ 0 ][ 0 ];
ip <= &rmat[ ROWCOUNT - 1 ][ COLUMNCOUNT - 1 ];
ip = ip + 1 )
printf( "memory at: %lx contains value: %d\n", (unsigned long) ip, *ip );
return( 0 );
}
我收到此错误:
$ cc minmatrix.c
minmatrix.c: In function ‘matriscopy’:
minmatrix.c:18:17: error: subscripted value is neither array nor pointer nor vector
minmatrix.c:18:32: error: subscripted value is neither array nor pointer nor vector
您能帮我理解吗?
推荐答案
您可以简单地使用memcpy
You can simply use memcpy
void matriscopy (void * destmat, void * srcmat)
{
memcpy(destmat,srcmat, ROWCOUNT*COLUMNCOUNT*sizeof(int));
}
destmat
和srcmat
的大小应相同.
此功能仅允许复制整个矩阵.
this function allow to copy only the whole matrix.
此功能无法从母矩阵复制子矩阵.
this function is not able to copy a sub matrix from the mother matrix.
示例:如果我有一个7列7行的矩阵.我无法使用上述功能从母矩阵复制子矩阵(4行4列).为此,我们必须逐个复制一个单元格
example: If I have a matrix with 7 column and 7 rows. I can not copy with the above function a sub matrix (4 rows and 4 columns) from the mother matrix. To Do it, we have to make a copy cell by cell
这篇关于如何在C中复制矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文