Permanent pointer array or pointer to an array? What is faster in C?

Hello, I am now in intermediate class C, and this thought occurred to me:

int multi[3][4]; // const multidimensional array

int* ptr = *multi; // ptr is a pointer variable that hold the address of multi const array

So what is faster / less / optimized to access the multi-dimensional position of the array?

It:

multi[3][1]; // index the value position

or

*(*(multi+2)+1); // pointer to the position on the array

or (UPDATED)

ptr += 9; // pointer arithmetic using auxiliary pointer

Since β€œmulti” is a const array, the compiler must already β€œknow” the localization of the position of the element, if you use a variable pointer pointing to this array, which may take longer to process, on the other hand, it may be faster when searching for the element I want display. What is a faster / smaller / optimized approach?

Thanks in advance.

+3
source share
5 answers

, *(pointer_to_first_element + x + y).

+8

-,

int multi[3][4];

const. const.

-,

int* ptr = *multi;

ptr multi[0][0]. multi[0] multi, .

-,

multi[3][1];

*(*(multi + 3) + 1);

. , , .

-,

*ptr + 9;

" ".

multi[0][0] + 9;

. , , , .

, " ", .

+6

, , , ; , .

:

int main(void)
{
  int arr[3][4] = {{0,1,2,3},{4,5,6,7},{8,9,10,11}};
  int *p = *arr; // == arr[0] == &arr[0][0]

  int x;

  x = arr[2][3];         // Straightforward array access
  x = *(*(arr+2)+3);     // Ugly pointer arithmetic
  x = *(ptr + 11);       // Slightly less ugly pointer arithmetic

  return 0;
}

gcc -c -g -Wa,-a,-ad > foo.lst, .

x = arr[2][3];:

movl      -16(%ebp), %eax     
movl      %eax, -8(%ebp)      

x = *(*(arr+2)+3);:

leal      -60(%ebp), %eax
addl      $44, %eax
movl      (%eax), %eax
movl      %eax, -8(%ebp)

, , x = *(ptr + 11);:

movl      -12(%ebp), %eax
addl      $44, %eax
movl      (%eax), %eax
movl      %eax, -8(%ebp)

. 1970-. gcc , , .

, , (FWIW, -O1 ), - ( ). , , . , .

, 2 3 , . *(ptr + offset); . . , .

+4

a[i] *(a+i), i[a], .

*(ptr+i) , ptr[j][k] , ( ptr[j][k] 2).

+2

, , , .

, .

, , , . .


, . C - , - " ", .. . ,

[]

* ( + I)

.

+1

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


All Articles