The question of C language arrays and Pointers is a very thought provoking question

  • 2020-06-12 10:09:10
  • OfStack

Recently written will encounter this problem, who all dare not say their own C/C + + can be proficient in, of course, work 1 for a long time, many old there would be easy to made, so theory is really important, this problem is, the truth and that kind of foundation, although was written by me to the right, but l still want to dig into the transformation of the specific details.

Such as:


#include <stdio.h>
int main(void)
{
 char *str[] = {"ab","cd","ef","gh","ij","kl"};
 char *t ;
 t = (str+4)[-1];
 printf("%s\n",t);
 return 0 ; 
}

May I ask the output result of the above program? The correct operation results of the program are as follows:

I was at 1 look, array index and negative values, right? What's going on here? Let's change the above program to 1 and it will be very clear, as follows:


#include <stdio.h>
int main(void)
{
 char *str[] = {"ab","cd","ef","gh","ij","kl"};
 char *t ;
// t = (str+4)[-1];
// printf("%s\n",t);
 t = (str+4)[0] ;
 printf("t:%s\n",t);
 return 0 ; 
}

The answer, of course, is ij.

Look at the picture above to get the result, which is actually a transformation relationship like this:

The compiler actually converts the array element form a[i] to * (a+i) before performing the operation. For the form of 1 general array elements: < An array of > [ < Subscript expression > ] the compiler converts it to: * ( < An array of > + < Subscript expression > ), where the subscript expression is: subscript expression * expansion factor. The calculation result of the whole formula is 1 memory address, and the final result is: * < address > = < The contents of the address of the cell to which the address corresponds > . As you can see, the C language's processing of arrays is actually an operation that translates into pointer addresses.

So, t = *(str+4);

Therefore, t = (str+4)[-1] ======= > t = *(str+4-1) ====== > t = *(str+3) ;

So:


#include <stdio.h>
int main(void)
{
 char *str[] = {"ab","cd","ef","gh","ij","kl"};
 char *t ;
// t = (str+4)[-1];
// printf("%s\n",t);
 t = *(str+4-1);
 printf("t:%s\n",t);
 return 0 ; 
}

Operation results:

If I write it differently, as follows:


#include <stdio.h>
int main(void)
{
 int b ;
 int a[10] = {1,2,3,4,5,6,7,8,9,10};
 int *p = &a[0] ;
 b = (p+8)[-4];
 printf("b:%d\n",b);
 return 0 ; 
}

Do you know what the answer is? 1 Sample algorithm:

Keep up the good work! Review the past and learn the new, pay attention to the foundation, 1 point details do not let go!

conclusion


Related articles: