C中的指针,从函数返回?
我正在尝试用C语言创建一个简单的矩阵乘法程序。 为此,我选择使用2个函数:1个用于简单创建矩阵,1个用于保存所有创建的矩阵以进行乘法 我终于设法解决了如何从函数传递数组,或者更具体地说,如何从函数传递指向数组的指针,但是,我希望下面的函数matrixWelcome传递数组的行数和列数。这就是我被困的地方 当前gcc为行->行=*i提供了“一元*”的错误无效类型参数 我的代码是:C中的指针,从函数返回?,c,pointers,C,Pointers,我正在尝试用C语言创建一个简单的矩阵乘法程序。 为此,我选择使用2个函数:1个用于简单创建矩阵,1个用于保存所有创建的矩阵以进行乘法 我终于设法解决了如何从函数传递数组,或者更具体地说,如何从函数传递指向数组的指针,但是,我希望下面的函数matrixWelcome传递数组的行数和列数。这就是我被困的地方 当前gcc为行->行=*i提供了“一元*”的错误无效类型参数 我的代码是: void matrixWelcome() { int selection; int a, b, c,
void matrixWelcome() {
int selection;
int a, b, c, d, *rows, *columns;
int *matrix1[0][0], *matrix2[0][0];
printf("Welcome to matrix mode\n");
printf("Please select from the following: \n");
printf("1 - Matrix multiplication");
scanf("%d", &selection);
switch (selection) {
case 1:
printf("Selected matrix multiplication...\n");
printf("Please enter matrix 1\n");
matrix1[*rows][*columns] = matrixInput(*rows, *columns);
printf("%d\n", *matrix1[1][1]);
a = *rows;
b = *columns;
printf("****ROWS = %d, COLUMNS = %d", a, b);
// printf("Matrix 1 has %d rows and %d columns", rows, columns);
printf("Please enter matrix 2\n");
// matrix2 = matrixInput();
break;
default:
printf("No input entered\n");
break;
}
}
int *matrixInput(int *rows, int *columns) {
int i, j, x, y;
int *array_pointer = malloc(5 * sizeof(int)); //grab some memory
if (array_pointer == NULL) { // check that we have successfully got memory
return NULL;
}
// Number of rows & columns for matrix 1
printf("Enter number of rows: ");
scanf("%d", &i);
printf("\nEnter number of columns: ");
scanf("%d", &j);
rows = *i;
columns = *j;
// Initialise 2D array to hold values
int matrix_input[i][j];
printf("Enter values for matrix, starting at 1,1 and moving across 1st row; then move across 2nd row etc..");
// loop to store values in matrix
for (x=0; x<i; x++) {
for (y=0; y<j; y++) {
int value_entered;
scanf("%d", &value_entered);
matrix_input[x][y] = value_entered;
}
}
*array_pointer = matrix_input[i][j];
// print out matrix - just to confirm
printf("You've entered the following matrix: \n");
for (x=0; x<i; x++) {
for (y=0; y<j; y++) {
printf("%4d", matrix_input[x][y]);
}
printf("\n");
}
return array_pointer;
}
任何帮助都将不胜感激。我是一个int。您不需要取消对它的引用。您确实需要取消对行的引用,但是-*rows=我可以正常工作。不过,在调用函数时不要取消引用。使用:
matrixInput(rows, columns);
因为你想通过指针
int *matrix1[0][0], *matrix2[0][0];
这是奇怪和不正确的,您不应该将全局变量声明为0维数组
您的代码不完整。您至少忘记了包含和还包含
而且你的代码不能编译
您应该尝试在启用所有警告的情况下进行编译,例如在Linux上使用
我收到4个错误和10多个警告
在没有警告和错误之前不要发布代码。编辑并改进代码,直到所有错误和警告消失。然后使用调试器(如Linux上的gdb)调试代码。w.r.t.标题:记住,指向对象的指针仅在该对象的生存期内有效。e、 g.函数返回后,指向函数中声明的数组的指针无效。函数返回指针的一个典型示例就是malloc,它通常是用C完全编码的,高于较低级别的系统调用,如mmapSorry-忘了提到这只是代码的一部分。我有很多其他的代码,包括库等。不过谢谢你的帮助:更具体地说,你不能取消对int的引用。它没有任何概念上的意义。谢谢你的帮助,我非常感激。当你说你不去引用整数,你怎么会去去引用行“*rows=i”?啊,是的,对不起,那太傻了。我现在得到一个分段错误:11当我运行程序编译时没有任何错误或警告。有什么建议吗?感谢您没有为行或列分配任何空间。
gcc -Wall -g cud.c -o cud