gpt4 book ai didi

c - 如何在C中复制矩阵?

转载 作者:太空狗 更新时间:2023-10-29 17:19:19 25 4
gpt4 key购买 nike

我正在尝试编写应该复制矩阵的函数 matricopy 但编译器提示:

/* 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

void matriscopy (void * destmat, void * srcmat) 
{
memcpy(destmat,srcmat, ROWCOUNT*COLUMNCOUNT*sizeof(int));
}

destmatsrcmat 应该有相同的大小。

这个函数只允许复制整个矩阵。

此函数无法从母矩阵复制子矩阵。

示例:如果我有一个包含 7 列和 7 行的矩阵。我无法使用上述功能从母矩阵复制子矩阵(4 行和 4 列)。为此,我们必须逐个单元地复制

关于c - 如何在C中复制矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12675800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com