C - 如何将 scanf 与 2D 数组一起使用以及如何将分配的数组作为函数的参数传递?



我一直在寻找和努力解决这个问题几个小时,我搜索了互联网,出于某种原因,每次我调整一个问题时都会弹出另一个问题

基本上,我想将用户的值转换为大小未确定的 2D 数组(我也将其作为输入(,然后我只想将此 2D 数组作为参数传递给像常规 2D 数组这样的函数( arr[k][numElements](

因为 unkown 中 2D 数组的大小我分配了 2D 数组,然后我尝试使用 scanf 将 valuse 输入到数组中,但我收到此错误:

下标值既不是数组,也不是指针也不是矢量

此外,当我尝试将数组传递给我的函数时,出现错误 (我宁愿不使用该功能,因为我非常努力地让它工作,哈哈(

int main()
{
int numElements;
int n; // number of elements
int k; // number of parts
scanf("%d",&n);
scanf("%d",&k);
numElements=n/k;
int length_of_array = k* numElements;
int *arr = (int *)malloc( length_of_array * sizeof(int));
for(int i=0 ; i<k ; i++){
for(int j=0 ; j<numElements ; j++){
scanf("%d", arr[k][numElements]);
}
}

int* output = (int*)malloc(sizeof(int)*n);

divide(0, k - 1, output, numElements,k, arr);
// Print merged array
printf("n________________________________________________________________n");
for(int i=0 ; i<n ; i++){
//scanf("%d",output+i);
printf("%d ",*(output+i));
}
}
//and this the function devide that i am trieng to pass the array to :
void divide(int l, int r, int* output, int numElements , int k ,  int arr[k][numElements] );

在这里我得到以下错误:

预期的"int (*([(sizetype((numElements(]",但参数的类型是 "int">

int main()
{
int n, m; // number of elements
scanf("%d",&n); // n no. of rows 
scanf("%d",&m); // m no. of columns
int arr[n][m]; //creating n*m memory spaces- runtime allocation
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<m ; j++){
scanf("%d", &arr[i][j]); //for each row takes n no. of column values
}
}
int* output = (int*)malloc(sizeof(int)*n);
divide(0,n-1,arr); //passing lower index, upper index , the array
// Print merged array
printf("n________________________________________________________________n");
for(int i=0 ; i<n ; i++){
//scanf("%d",output+i);
printf("%d ",*(output+i));
}
}

最新更新