在函数中使用二维数组:错误 [英] Using a 2D Array in Function: Error

查看:47
本文介绍了在函数中使用二维数组:错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在二维数组中设置值并使用函数打印它.

I tried to set values in 2D array and Print it with Function.

但是我无法将数组发送到函数.

but I got trouble to send the Array to the Function.

#include <stdio.h>

void SetArr(int (*arr)[], int n);
void PrintfArr(int (*arr)[], int n);

int main()
{ 
    int arr[100][100];

    for(int i=0; i<100; i++)
        for(int j=0; i<100; j++)
            arr[i][j]=0;         //initiallize Array

     int size;

    printf("input Size : "); scanf("%d", &size);

    SetArr(arr, size);
    PrintfArr(arr, size);

    return 0;
}

void SetArr(int (*arr)[], int n)
{
   int i, j;

    for(i=0; i<n; i++)
   {
       for(j=0; j<n; j++)
            arr[i][j]=i+j;    // Error! "Subscript of Pointer to imcomplete~
   }
}

void PrintArr(int (*arr)[], int n)
{
   int i, j;

   for(i=0; i<n; i++)
   {
       for(j=0; j<n; j++)
           printf("%d", arr[i][i]);  // Error! "Subscript of Pointer to imcomplete~
   }
   printf("\n");
}

如您所见,两个函数在使用 "arr[][]" 时都遇到了同样的问题

As you see, both of functions got same problem while using "arr[][]"

推荐答案

在函数的声明中,必须提到数组的大小(长度).这就是编译器说不完整类型"时的意思:它需要大小来了解如何访问其元素.

In the declaration of the function, array must be mentioned with its size (length). This is what the compiler means when it says "incomplete type": it needs the size to understand how to access its elements.

为了使编译器可以使用大小,它应该首先出现在函数的声明中:

In order to make size available to the compiler, it should go first in the function's declaration:

void SetArr(int n, int (*arr)[n])

这里的 arr 在技术上是指向 n 个元素的数组的指针",但在 C 中习惯上将指针视为数组,所以 arr 可以视为n 个元素的数组的数组",与二维数组相同.

Here arr is technically a "pointer to an array of n elements", but in C it's customary to treat a pointer as an array, so arr can be treated as "an array of arrays of n elements", which is the same as a 2-D array.

您可能想提及数组的两个维度:

You might want to mention both dimensions of the array:

void SetArr(int n, int arr[n][n])

这相当于第一个声明,但看起来更清晰.

This is equivalent to the first declaration, but seems clearer.

这篇关于在函数中使用二维数组:错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆