[Syntax C] 数组和指针
重点是如何对一个负责的变量的定义进行抽丝剥茧。
如:
char *c3[][2] = { {"a1", "a2"}, {"b1", "b2"}, {"c1", "c2"}, }; char *(*c3_1)[2]; // (*c3_1):c3_1是个指针; (*c3_1)[2]:该指针指向长度为2的数组; char *(*c3_1)[2]:该数组存放char* 类型的数据 c3_1 = c3; printf("c3_1 = %s\n", c3_1[0][0]); // a1
当数组和指针交织在一起时:
char *c1 = "abcde"; printf("sizeof c1 = %d\n", sizeof c1); // 指针长度,8byte printf("strlen(c1) = %d\n", strlen(c1)); // 5 char c2[] = "abcde"; printf("sizeof c2 = %d\n", sizeof c2); // 数组长度,6byte,有'\0' printf("strlen(c2) = %d\n", strlen(c2)); // 5 char *c3[][2] = { {"a1", "a2"}, {"b1", "b2"}, {"c1", "c2"}, }; char *(*c3_1)[2]; // (*c3_1):c3_1是个指针; (*c3_1)[2]:该指针指向长度为2的数组; char *(*c3_1)[2]:该数组存放char* 类型的数据 c3_1 = c3; printf("c3_1 = %s\n", c3_1[0][0]); // a1 printf("sizeof c3 = %d\n", sizeof c3); // 6个指针,48byte printf("strlen(c3) = %d\n", strlen(*c3[0])); // 2, "a1"的长度 printf("strlen(c3) = %s\n", *c3[0]); // a1 char *c4[][2] = { {"x1", "x2"}, {"y1", "y2"}, {"z1", "z2"}, }; char *(*c5[])[] = { // (*c5[]):c5是指针数组; (*c5[])[]:数组中的指针指向另一个数组; char *(*c5[])[]:该数组存放了char*类型的数据 c3, c4 }; char *(*c6)[2] ; // c6是个指针,指向长度是2的数组,数组存放了char*类型的数据 c6 = c5[1]; printf("c6[0][1] = %s\n", c6[0][1]); // x2,最直接的方式 printf("(*c6)[0]) = %s\n", (*c6)[0]); // x1,(*c6):指针指向第一行; (*c6)[0]:指针指向第一行第一列 printf("**c6 = %s\n", **c6); // x1, 原理同上 printf("(*c6)[1] = %s\n", (*c6)[1]); // x2,原理同上 printf("(*c6 + 1)[1] = %s\n", (*c6 + 1)[1]); // y1, (*c6 + 1):指针指向"x2";(*c6 + 1)[1]:指针指向下一个char*,也就是"y1" printf("(*(c6 + 1))[1] = %s\n", (*(c6 + 1))[1]); // y2, *(c6 + 1)):由于数组长度是2,所以c6每+1就跳过2个char*,故指向"y1";(*(c6 + 1))[1]:指向"y2" printf("*((*c6 + 1)+1) = %s\n", *((*c6 + 1)+1)); // y1, 原理同上