【发布时间】:2017-03-28 22:44:25
【问题描述】:
我无法打印出存储在数组中的值。它似乎正在打印出内存地址。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void getMatrix(int x, int y);
void printMatrix(int arr[], int x, int y);
int product(int arr1[], int arr2[]);
int main(void){
//Variables that will store matrix size
int m, n, o, p;
//Prompt user for size of Matrix A
printf("Enter the rows and columns of Matrix A with space in between: ");
//Read input
scanf("%d %d", &m, &n);
//Prompt user for the size of Matrix B
printf("Enter the rows and columns of Matrix B with space in between: ");
//Read input
scanf("%d %d", &o, &p);
//Seed RND Generator
srand(time(NULL));
//Check input
if(n != o){
while(n != o){
printf("Matrix Sizes are not valid. Please enter valid sizes for the Matrices: ");
scanf("%d %d %d %d", &m, &n, &o, &p);
}
}
//Function Calls
printf("Matrix 1:\n");
getMatrix(m, n);
printf("\nMatrix 2:\n");
getMatrix(o, p);
}
void getMatrix(int x, int y){
//Counter
int c;
//Size Declaration
int size = x * y;
//Array Declaration
int arr[size];
for(c = 0; c < size; c++){
arr[c] = rand()%10;
}
printMatrix(arr[size], x, y);
}
void printMatrix(int arr[], int x, int y){
//Counters
int i, j;
for(i = 0; i < y; i++){
printf("\n");
for(j = 0; j < x; j++){
printf("%d ", arr[j]);
}
}
}
所以基本上这段代码应该接受输入并创建一个可变长度数组,它应该将随机数存储在一维数组中,然后它们必须以二维数组或矩阵的形式打印出来。我感觉printMatrix函数的参数或者传递getMatrix函数中得到的数组时可能有问题。任何帮助将不胜感激,谢谢。
编辑:谢谢大家的帮助。我什至没有考虑将其用作解决方案。但它现在可以工作并打印出它应该打印的数字。再次感谢
【问题讨论】:
-
我确信编译器在向你抱怨,而你却忽略了它的抱怨,它试图提供帮助。它在这条线上抱怨
printMatrix(arr[size],... -
尝试将
printMatrix(arr[size], x, y);更改为printMatrix(arr, x, y); -
您应该会收到
printMatrix(arr[size], x, y);行的错误。如果你不这样做,那么首先要做的是调整你的编译器设置,直到你得到一个错误。然后修复错误。 -
在
getMatrix():printMatrix(arr[size], x, y);-->printMatrix(arr, x, y);和printMatrix():printf("%d ", arr[j]);-->printf("%d ", arr[i * x + j]); -
我试过使用'printMatrix(&arr[size], x, y);'而不仅仅是 'arr[size]' 并且确实消除了所有编译器注释和错误,但它仍然不会打印出数组中的随机数