gpt4 book ai didi

c - 如何在 C 中声明可变大小的数组?

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:11 29 4
gpt4 key购买 nike

好吧,我正在做矩阵乘法,我需要制作一个 m x n 数组和一个 p x q 数组。
但是,我不知道该怎么做。

这是我的程序,当我手动输入值时它会打印正确的输出:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
/*
Rows and columns for matrices.
*/
int m , n; // rows and columns of the first matrix
int p , q; // rows and columns of the second matrix

/*
1st matrix is a 2x3 matrix
*/
m = 2;
n = 3;

/*
2nd matrix is a 3x2 matrix
*/
p = 3;
q = 2;


/*
Create the matrices.
Give them values.
*/
int matrix1[m][n] = {
{2,3,4},
{5,6,7}
};
int matrix2[p][q] = {
{1,7},
{3,9},
{5,11}
};

/*
Check if we can multiple the matrices.
For matrix multiplication,
the number of COLUMNS of FIRST matrix must be equal to
the number of ROWS of SECOND matrix
*/
if(n==p){
/*
Create a new matrix.
The resulting matrix will have M rows and Q columns.
That is, the matrix is a MxQ matrix.
*/
int matrix3[2][2];

/*
We need three loops so we have 3 variables.
*/
int i = 0; // iterates over matrix1 rows
int j = 0; // iterates over matrix1 columns
int k = 0; // iterates over matrix2 rows
int l = 0; // iterates over matrix2 columns


while(i < m){
l = 0;
while(l < q){
int element = 0;
while(j < n && k < p){
element += matrix1[i][j] * matrix2[k][l];
matrix3[i][l] = element;
j++;
k++;
}
printf("\t%d",element);
l++;
j = 0;
k = 0;
}
printf("\n");
i++;
}

}else{
printf("Matrices can not be multiplied");
}
}

矩阵声明被标记为错误。 我该如何解决?

最佳答案

How do I solve it?

首先,不使用 VLA。对于此特定任务,您不需要 VLA。

至于实际问题是什么:可变长度数组无法初始化。您必须一个一个地分配给它们的元素,或者使用一些批量“分配”技术,例如 memcpy()

关于c - 如何在 C 中声明可变大小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18936855/

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