2017-01-04 7 views
2

2次元配列の最初の行を指すように次のコードを記述しました。私は2次元配列の特定の行を指します

arrayPtr = & array[0]; 

を行うときしかし、私は

error: cannot convert double (*)[1] to double* in assignment

arrayPtr = & array[0]; 

私のプログラムがあるなって終わる:

#include <iostream> 

int main(int argc, char **argv) 
{  
    double array[2][1]; 

    array[0][1] = 1.0; 
    array[1][1] = 2.0; 

    double* arrayPtr; 
    arrayPtr = &array[0]; 

    return 0; 
} 

を誰かが私が間違っているつもりどこにとして理解するのに役立つことはできますか?

+1

です。これはCではない。 – Olaf

答えて

2

代わりのarrayPtr = & array[0]、あなたは、配列の減衰特性を利用するために

arrayPtr = array[0]; 

を書くことができます。

関連、

C11を引用
  • 、チャプタ§6.3.2.1、左辺値、配列、および機能指定子C++14を引用

    Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

  • 、章§5.3.3

    The lvalue-to-rvalue (4.1) , array-to-pointer (4.2) , and function-to-pointer (4.3) standard conversions are not applied to the operand of sizeof .

    と、章4.2

    An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

ため代入演算子のRHSオペランドとして用いつつ、array[0]は、配列の最初の要素へのポインタに減衰する、すなわち、型を生成しますdouble*は、LHSと同じです。

&演算子を使用すると、タイプdouble [1]の配列であるarray[0]の配列減衰が防止されます。

したがって、&array[0]は、割り当てのLHSに供給される変数の種類と互換性がdouble *ないdouble [1]のアレイ、又は、double (*) [1]へのポインタである型を返します。あなたのコードで

+0

働いた、なぜそうですか? –

+0

申し訳ありませんが、「配列の崩壊」とはどういう意味ですか? –

+0

@AlexanderFell better? –

2

  • arrayはタイプdouble (*)[1]です。 T*に減衰することができT[]
  • array[0]注1

(これはarrayに等しい)(double[1]へすなわちポインタ)タイプdouble (*)[1]であるタイプのdouble[1]

  • &array[0]あります。だからあなたの例ではdouble[]は腐敗する可能性がありますdouble *

    注2:a[b] == *(a + b)ので、あなたの例では&array[0]array自体に簡略化されて& (*(array + 0))に等しいです。

  • 1
    double array[2][1]; 
    double* arrayPtr; 
    arrayPtr = & array[0]; 
    

    arrayPtrarrayがタイプ

    POINTER(POINTER(DOUBLE)) 
    

    &array[0]あなたがassigしようとするタイプ

    POINTER(POINTER(DOUBLE)) 
    

    を持っていながらタイプ

    POINTER (DOUBLE) 
    

    を持っていますそれを行うためのn

    POINTER (DOUBLE) <= POINTER(POINTER(DOUBLE)) 
    

    正しい方法ではないスパムのタグを行い

    arrayPtr = array[0]; 
    

    または

    arrayPtr = *array; 
    
    +0

    2番目と3番目のオプションは、最初のものと同等ではないため、間違っています。多分 'arrayPtr = * array'を意味するでしょうか? –

    +0

    @KiJéyありがとう、訂正しました。 – alinsoar