【发布时间】:2020-07-20 14:13:51
【问题描述】:
您好,我正在处理用户输入多个不同长度的连续数组的场景,我想存储这些数组以供进一步使用。
我为此目的使用多维数组。 这是代码:
#include <stdio.h>
int main()
{
int rows,cols;
printf("Enter the number of user input arrays ? ");
scanf("%d",&rows);
printf("Enter the maximum number of inputs in a single array ?"); //Need to remove these lines
scanf("%d", &cols); //Need to remove these lines if possible
int array[rows][cols];
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
array[i][j]=0;
}
}
for(int i=0;i<rows;i++)
{
int count;
printf("Enter the number of inputs for array %d - ", i);
scanf("%d",&count);
for(int j=0;j<count;j++)
{
scanf("%d",&array[i][j]);
}
}
//// Use array for other purpose
////printf("\n\nArray --> \n");
////for(int i=0;i<rows;i++)
////{
////for(int j=0;j<cols;j++)
////{
////printf("%d ",array[i][j]);
////}
////printf("\n");
////}
return 0;
}
示例输入:
输入用户输入数组的数量? 5
输入单个数组中的最大输入数 ?5
输入数组 0 - 5 的输入数量
1 2 6 3 5
输入数组 1 - 1 的输入数量
3
输入数组 2 - 2 的输入数量
6 5
输入数组 3 - 1 的输入数量
3
输入数组 4 - 1 的输入数量
9
在这种情况下创建的数组:
1 2 6 3 5
3 0 0 0 0
6 5 0 0 0
3 0 0 0 0
9 0 0 0 0
现在我在这种情况下遇到了一些问题:
-
我想通过删除数组中不必要的条目来减少使用的空间。
-
我不想使用“0”或任何其他整数来定义不必要的条目,因为它是有效的输入。
-
我想删除该行
printf("输入单个数组的最大输入数?"); scanf("%d", &cols);
谁能帮我解决这些问题。
【问题讨论】:
-
这将需要创建和重新创建指针数组,每个指针的容量由运行时用户输入决定。做到这一点的唯一方法是动态分配内存,使用 [c][m]alloc 和可能的 realloc。这是您的预期吗?
-
为什么不想要
"Enter the maximum number of inputs in a single array ?"这一行,用户怎么知道该怎么做? -
您可能会从了解更多关于 sparse matrices 的信息中受益。
-
@ryyker 那么它会像锯齿状数组还是其他东西,我只需要在第一个输入中获取总数组,然后根据用户输入决定内部数组的大小。
-
@FredLarson - 稀疏矩阵是否提供超出初始定义的运行时修改?