c language (pointers are used as array processing array names are used as pointers)

 
 
Pointers are used as array handling
  1. #define N 10
  2. int a[N], sum, *p;
  3. ....
  4. sum = 0;
  5. for(p = &a[0]; p < &a[N]; p++)
    1. sum += *p;

Use the array name as a pointer
You can use the name of the array as a pointer to the first element of the array
int a[10]
Using a as a pointer to the first element of the array, you can modify a[0]
*a = 7;
a[1] can be modified by the pointer a + 1
*(a + 1) = 12;
usually, a + i is equivalent to &a[i] (both represent pointers to element i in array a), and *(a + i) is equivalent to a[i]
(Both represent the element i itself), that is, the subscripting operation of the array can be regarded as a form of pointer arithmetic.

for(p = &a[0]; p < &a[N]; p++)
sum += *p;
  • To simplify the loop, replace &a[0] with a and &a[N] with a + N
for(p = a; p < a +N; p++)
sum += *p;

example:
1. Reverse print input character program ( pointer is used for array processing )
#include <stdio.h>
#define MSG_LEN 80     /* maximum length of message */
int main(void)
{
  char msg[MSG_LEN], *p;

  printf("Enter a message: ");
  for (p = &msg[0]; p < &msg[MSG_LEN]; p++) {
    *p = getchar();
    if (*p == '\n')
      break;
  }

  printf("Reversal is: ");
  for (p--; p >= &msg[0]; p--)
    putchar(*p);
  putchar('\n');

  return 0;
}

2. 逆向打印输入字符程序 ( 数组名用作指针 )
#include <stdio.h>

#define MSG_LEN 80     /* maximum length of message */

int main(void)
{
  char msg[MSG_LEN], *p;

  printf("Enter a message: ");
  for (p = msg; p < msg + MSG_LEN; p++) {
    *p = getchar();
    if (*p == '\n')
      break;
  }

  printf("Reversal is: ");
  for (p--; p >= msg; p--)
    putchar(*p);
  putchar('\n');

  return 0;
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647256&siteId=291194637