Iterate over a two-dimensional array using a single char pointer

Carrying out some research on multidimensional arrays in C and how they are stored in memory, I came across this: " Does C99 guarantee that arrays are contiguous? ". The response to the upper voice states that “it should also be possible to iterate over the entire array using (char *)”, and then provides the following “valid” code:

int  a[5][5], i, *pi;
char *pc;

pc = (char *)(&a[0][0]);
for (i = 0; i < 25; i++)
{
    pi = (int *)pc;
    DoSomething(pi);
    pc += sizeof(int);
}

Then the poster says, "Doing the same with (int *) would be undefined behavior because, as said, an array [25] of int is not involved."

This line confuses me.

Why is using a char pointer a valid / specific behavior when substituting it with an integer pointer?

, .: (

+4
3

char* int* - : (&a[0][0])[6] (.. int*), , [6] a[0]. , , (&a[0][0]) + 6 a[1] + 1 , , .

char* - , : - char* undefined.

+3

, :

int a[5];
int* p = &a[0];

p += 6;

undefined.

, , 2D-,

int a[5][5];

. , :

int* p1 = &a[0][0];
int* p2 = &a[1][0];

p1+5 , , a, p2. , :

int* p3 = p1 + 6;

int* p3 = p2 + 1;

p2 + 1 , p1 + 6 ?

p1 + 6 undefined. , , , 2D-.

p1 + 6.
p1 + 6 - undefined.

+1

int char, . , sizeof(int) 4. pc += sizeof(int) 4 , pi += sizeof(int) 4 4 . int, pi ++.

EDIT: , int C99 ( ). : , . int, a[0], a[1]. a[0] int ( ) a[1].

. char , , :

, memset, memmove memcpy sizeof. (char *).

6.5.6 " "

, , .

.

0

Source: https://habr.com/ru/post/1626812/


All Articles