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

前端 未结 5 1753
渐次进展
渐次进展 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:21

    Here v[i] stands for integer array of 5 elements.. and an integer array is referenced by an address location which depending on your 'c' compiler could be 16 bits, 32 bits...

    so v[i] = i may compile in some compilers.... but it definitely won't yield the result u are looking for.

    Answer by sharptooth is correct v[i][j] = i... is one of the easiest and readable solution..

    other could be

    int *ptr;
    ptr = v;
    

    now u can iterate over this ptr to assign the values

    for (i = 0; i < 5*5; i++, ptr++) {
         *ptr = i;
    }
    

提交回复
热议问题