Access to the declared border on structural elements or in each dimension of a multidimensional array

Can anyone give me an example for this statement. I read it somewhere where it was mentioned that this kind of using a pointer is not recommended.

"Access to the declared border on structural elements or each dimension of a multidimensional array."

+3
source share
2 answers

This boils down to easy access outside the array:

int array[100];
int* pointer = array;
*(pointer + 100) = 0; // undefined behavior - the last valid index is 99
int value = *(pointer + 200); //undefined behavior just as well

any attempt to access elements outside the array leads to undefined behavior, which, firstly, leads to the failure of your program, data corruption and the like. This is not what you call not recommended, what you call , never do it .

0

, , - .

( malloc) ( libc) ( ) . , , , , .

char x[5];
int y;
short z;

Raw memory: (just an example, likely to vary)
         00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
b0000000 xx xx xx xx xx -- -- -- yy yy yy yy zz zz -- --

xx, yy zz x, y z, - . x[4], x+sizeof(x[0])*4 ( C: , ), b0000004. x[8], b0000008, y . x[8], y!

( , ):

char x[5];
int y;
short z;

y = 0x12345678;
x[8] = 0xad;
x[9] = 0xde;

printf("%#x\n", y);
/* 0x1234dead is printed ?!? */
+1

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


All Articles