【发布时间】:2016-03-14 16:52:44
【问题描述】:
下面是我正在使用的代码。当我运行它并注释掉处理addArrays 函数的代码时,它工作得非常好。
我相信我没有在 addArrays 函数中正确使用指针。任何帮助将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void addArrays(int rowSize, int columnSize, int Array1[rowSize][columnSize],
int Array2[rowSize][columnSize],
int *sumloc[rowSize][columnSize]);
void printArray(int rowSize, int columnSize, int arrayValue[rowSize][columnSize]);
/*
This program will make 2 2D matrices out of a random number of rows, 3 columns, and a random set of values.
Then, the two matrices will be added and all three printed.
*/
int main() {
//To get a true random number
srand(time(NULL));
int rowSize = rand() % 4 + 1;
int columnSize = 2;
int Array1[rowSize][columnSize];
int Array2[rowSize][columnSize];
int Arraysum[rowSize][columnSize];
//For loop counter
int col;
int row;
//Makes a unique number for each part of both arrays from 0-50
for (row = 0; row <= rowSize; row++)
for (col = 0; col <= columnSize; col++)
Array1[row][col] = rand() % 50;
for (row = 0; row <= rowSize; row++)
for (col = 0; col <= columnSize; col++)
Array2[row][col] = rand() % 50;
//Add arrays
addArrays(rowSize, columnSize, Array1[rowSize][columnSize],
Array2[rowSize][columnSize],v&Arraysum[rowSize][columnSize]);
//Utilizes the print function
printArray(rowSize, columnSize, Array1);
printArray(rowSize, columnSize, Array2);
printArray(rowSize, columnSize, &Arraysum);
return 0;
}
void addArrays(int rowSize, int columnSize, int a1[rowSize][columnSize],
int a2[rowSize][columnSize],
int *sumloc[rowSize][columnSize]) {
int row;
int col;
sumloc[rowSize][columnSize] = malloc(rowSize * columnSize * sizeof(int));
for (row = 0; row <= rowSize; row++)
for (col = 0; col <= columnSize; col++)
*sumloc[row][col] = a1[row][col] + a2[row][col];
return;
}
void printArray(int rowSize, int columnSize, int arrayValue[rowSize][columnSize]) {
int row;
int col;
for (row = 0; row <= rowSize; row++) {
printf("\n");
printf("[");
for (col = 0; col <= columnSize; col++) {
printf(" %d ", arrayValue[row][col]);
}
printf("]");
}
printf("\n\n");
return;
}
【问题讨论】:
-
你没有说你得到了什么错误(编译?运行时?什么消息?)你调用的函数是错误的。您正在使用声明来调用它。类型已经是
int[][],所以只需传递名称:addArrays(rowSize, columnSize, Array1, Array2, &Arraysum);。您可能还想为您的数组考虑更合理的名称。 -
所有这些
<=运算符似乎都不正确。