C/C++: Is this undefined behavior? (2D arrays)

前端 未结 5 1756
渐次进展
渐次进展 2020-12-04 02:29

Is it undefined behavior if I go through the elements of a 2D array in the following manner?

int v[5][5], i;

for (i = 0; i < 5*5; ++i) {
     v[i] = i;
}         


        
5条回答
  •  春和景丽
    2020-12-04 03:33

    This will not compile.

    You will get the following error for the line:

    v[i] = i;
    

    error: incompatible types in assignment of ‘int’ to ‘int [5]’

    To give an answer taken from a similar question at:

    http://www.velocityreviews.com/forums/t318379-incompatible-types-in-assignment.html

    v is a 2D array. Since you are only referencing one dimension, what you end up getting is a char pointer to the underlying array, and hence this statement is trying to assign a char constant to a char pointer. You can either use double quotes to change the constant to a C-style string or you can explicitly reference v[i][0] which is what I assume you intended.

提交回复
热议问题