Pointers are used as array handling
- #define N 10
- int a[N], sum, *p;
- ....
- sum = 0;
- for(p = &a[0]; p < &a[N]; p++)
- 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;
}
#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;
}
#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;
}