第28课 指针和数组分析(上)

数组的本质:

示例程序:

指针的运算:

指针的比较:

示例程序:

 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     char s1[] = {'H', 'e', 'l', 'l', 'o'};
 6     int i = 0;
 7     char s2[] = {'W', 'o', 'r', 'l', 'd'};
 8     char* p0 = s1;
 9     char* p1 = &s1[3];
10     char* p2 = s2;
11     int* p = &i;
12     
13     printf("%d
", p0 - p1);
14     printf("%d
", p0 + p2);
15     printf("%d
", p0 - p2);
16     printf("%d
", p0 - p);
17     printf("%d
", p0 * p2);
18     printf("%d
", p0 / p2);
19     
20     return 0;
21 }

根据以上的分析,14、16、17、18行都是不合法的。15行可以编译通过,但是没有意义,因为两个指针不是指向同一个数组中的元素的。

示例程序:

 1 #include <stdio.h>
 2 
 3 #define DIM(a) (sizeof(a) / sizeof(*a))
 4 
 5 int main()
 6 {
 7     char s[] = {'H', 'e', 'l', 'l', 'o'};
 8     char* pBegin = s;
 9     char* pEnd = s + DIM(s); // Key point
10     char* p = NULL;
11     
12     printf("pBegin = %p
", pBegin);
13     printf("pEnd = %p
", pEnd);
14     
15     printf("Size: %d
", pEnd - pBegin);
16     
17     for(p=pBegin; p<pEnd; p++)
18     {
19         printf("%c", *p);
20     }
21     
22     printf("
");
23    
24     return 0;
25 }

运行结果如下:

小结:

原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9538561.html