关于C语言数组操作的两个例子
第一个数组操作的例子:
They are not equal
Of course a is equal to a
a[0] = 2
a[1] = 3
第二个数组操作的例子:
oneWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 0
antherWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 10
#include <stdio.h> int main(void) { int a[2] = {1,2}; // 用集合的方式给数组赋值 int b[2] = {2,3}; int i; // 在等号左右两边使用数组下标是合法的 for(i=0;i<2;i++) a[i]=b[i]; // 数组直接赋值是不合法的,例如 a=b; // 即使两个具有相同值的数据进行直接比较也会返回 false if(a==b) printf("They are equal\n"); else printf("They are not equal\n"); // 下面的比较结果为 true if(a==a) printf("Of course a is equal to a\n"); else printf("No, a is not equal to a\n"); // 比较两个数组的地址才是有效的,而比较内容无效 // 不能将数组一次性输出,必须一个元素一个元素的循环输出 for(i=0;i<2;i++) printf("a[%1d] = %3d\n", i, a[i]); }输出结果:
They are not equal
Of course a is equal to a
a[0] = 2
a[1] = 3
第二个数组操作的例子:
#include <stdio.h> #define N 10 void oneWay(void); void anotherWay(void); int main(void) { printf("\noneWay:\n"); oneWay(); printf("\nantherWay:\n"); anotherWay(); } // 以集合的方式初始化数组 void oneWay(void) { int vect[N] = {1,2,3,4,5,6,7,8,9,0}; int i; for (i=0; i<N; i++) printf("i = %2d vect[i] = %2d\n", i, vect[i]); } // 循环初始化数组 void anotherWay(void) { int vect[N]; int i; for (i=0; i<N; i++) vect[i] = i+1; for (i=0; i<N; i++) printf("i = %2d vect[i] = %2d\n", i, vect[i]); }输出结果:
oneWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 0
antherWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 10