【发布时间】:2021-12-23 11:08:54
【问题描述】:
我被要求获取一个 4x5 的矩阵并扫描每一行(这就是 for 方法的原因),然后打印前半部分,然后打印后半部分。
我相信问题不在函数内部,因为它们在数组上运行良好
当它尝试打印时,我得到随机数和零 -
0.000000
-107374176.000000
-107374176.000000
-107374176.000000
-107374176.000000
0.000000
-107374176.000000
-107374176.000000
-107374176.000000
-107374176.000000
0.000000
164582.031250
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
846674930930036512480361854271488.000000
0.000000
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void scanFloats(float** arr, int size); // scans the floats
void printFloats(float* arr, int size); // prints the floats
int main()
{
float matrix[4][5];
for (int i = 0; i < 4; i++)
{
scanFloats(matrix[i], 5);
}
printFloats(matrix, 10);
printFloats(matrix + 10, 10);
}
void scanFloats(float** arr, int size)
{
*arr = malloc(sizeof(float) * size);
for (int i = 0; i < size; i++) {
printf("Enter number\n");
scanf("%f", (*arr) + i);
}
}
void printFloats(float* arr, int size)
{
for (int i = 0; i < size; i++)
{
printf("%f\n", *(arr + i));
}
}
【问题讨论】:
-
不要使用 malloc 数组已经分配了
-
请在编译时出现警告:
foo.c:14:20: warning: passing argument 1 of 'scanFloats' from incompatible pointer type...foo.c:5:6: note: expected 'float **' but argument is of type 'float *',其他函数也一样。 -
想一想:
matrix[i]是什么类型 -
我想了更多关于它提供了什么。 Matrix[i] 将提供我想要的地址+i,以单独扫描每一行。我怎样才能以正确的方式做到这一点?
-
我会说试试
printFloats(&matrix[2][0], 10);,但即便如此,你还是在滥用数组,假装它不是二维的
标签: c function pointers matrix