c - 如何将 scanf 与二维数组一起使用以及如何将分配的数组作为参数传递给函数?

标签 c arrays 2d

我已经搜索并尝试解决这个问题几个小时了,我搜索了互联网,由于某种原因,每次我调整一个问题时都会弹出另一个问题

基本上我想将用户的值输入到一个二维数组,它的大小是未知的(我也将它作为输入),然后我只想将此二维数组作为参数传递给像常规二维这样的函数数组 ( arr[k][numElements] )

因为二维数组的大小未知,所以我分配了二维数组,然后我尝试使用 scanf 向数组输入值,但出现此错误:

subscripted value is neither array nor pointer nor vector

此外,当我尝试将数组传递给我的函数时,我收到错误 (我不想改变这个功能,因为我非常努力地让它工作,哈哈)

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] );

这里我收到以下错误:

expected 'int (*)[(sizetype)(numElements)]' but argument is of type '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));
    }
}

关于c - 如何将 scanf 与二维数组一起使用以及如何将分配的数组作为参数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57911458/

相关文章:

c - pjsip铃声和应答码

javascript - 删除重复项并汇总数量

java - 需要 N Queens 程序的帮助(检查对角线)

iphone - 在 iPhone 的 Quartz 2D 中进行旋转变换时可以移动原点吗?

c++ - 将轴对齐的矩形旋转 90 度

c - 执行不在堆栈上的 shellcode(缓冲区溢出)

c - C 中的返回值

c++ - 在 C 程序中使用 C++ 代码,反之亦然

c++ - 通过指针访问数组元素

python - 如果段长度高于特定值,如何递归离散化段