3

配列を引数として渡すと、それをポインターとして受け入れます。つまり、次のようになります。

func(array);//In main I invoke the function array of type int and size 5

void func(int *arr)

or

void fun(int arr[])//As we know arr[] gets converted int *arr

ここでは、ベース アドレスが に格納されarrます。

しかし、渡された配列がこの方法で受け入れられた場合:

void func(int arr[5])//Works fine.

メモリは arr[5] に割り当てられますか?

はいの場合、それはどうなりますか?

いいえの場合、メモリが割り当てられていないのはなぜですか?

4

4 に答える 4

3

メモリは arr[5] に割り当てられますか?

いいえ、そうではありません。

いいえの場合、メモリが割り当てられないのはなぜですか?

必要ないからです。配列は、関数に渡されると、常にポインターに崩壊します。したがって、配列はポインターではなく、ポインターも配列ではありませんが、関数の引数では、次のコードは同等です。

T1 function(T2 *arg);
T1 function(T2 arg[]);
T1 function(T2 arg[N]);
于 2013-08-03T15:57:22.517 に答える
0

次のコード/コメントがお役に立てば幸いです。C をコーディングするとき、プログラマーはさまざまなプログラムで多くの項目が一致していることを確認する必要があります。これは、C でのプログラミングの楽しみでもあり、悩みの種でもあります。

ノート。パラメーター リストで定義int arr[5]しても、渡されるデータ用のストレージは割り当てられません。宣言は有効で承認されていますが、それはコンパイラが型チェックを実行できるようにするためです。ただし、関数が呼び出されたときにコンパイラはストレージを割り当てますが、そのストレージはあなたのデータを格納しません。malloc明示的な宣言 (次の例の main のように) によってデータを割り当てるか、ステートメントを発行する必要があります。

Eclipse/Microsoft C コンパイラで次のコードを実行しましたが、NO ステートメントに警告またはエラーのフラグが立てられました。

    //In main invoke the functions all referring the same array of type int and size 5

    void func1(int *arr)
    { // arr is a pointer to an int.  The int can be the first element
      // of an array or not.  The compiler has no way to tell what the truth is.
    }

    void func2(int arr[])
    { // arr is a pointer to an array of integers, the compiler can check this
      // by looking at the caller's code.  It was no way to check if the number
      // of entries in the array is correct.
    }

    void func3(int arr[5])
    { // arr is a pointer to an array of 5 integers.  The compiler can
      // check that it's length is 5, but if you choose to overrun the
      // array then the compiler won't stop you.  This is why func1 and func2
      // will work with arr as a pointer to an array of ints.
    }

    void main()
    {
      int data_array[5] = {2,3,5,7,11};

      func1(data_array);

      func2(data_array);

      func3(data_array);

    }

これがお役に立てば幸いです。詳細についてはお問い合わせください。

于 2013-08-03T19:15:30.690 に答える