我总结了一些常见的C类型声明,现在我想知道一些可靠的例子,例如:如何初始化它们以及如何使用它们。
已经给出了一些例子,但有些例子还在等待好的例子。
【int p[3]; int *p[3]; int p[][3]; int (*p)[3]; int *(p[3]); int (*p[8])[5];
】
【char p[3]; char *p[3]; char p[][3]; char (*p)[3]; char *(p[3]); char (*p[8])[5];
】
【int **p; char **p;
】
int p[3];
//p is array of 3 int.
示例:
int contestants[] = {1, 2, 3};
-
char p[3];
//p is array of 3 characters.
示例:
char cards[] = "JQK";
-
int *p[3];
//p is array of 3 pointers to int.
示例:
int x = 1;
int y = 2;
int z = 3;
int *a1[3] = {&x, &y, &z}; //array of pointer to int
printf (" &x = %p, a1[0] = %p\n" , &x, a1[0]);
printf ("%d %d %d\n" , *a1[0], *a1[1], *a1[2]); //1 2 3
-
int p[][3];
//p is array of array of 3 int.
示例:
int data1[2][3] = { {1,2,3}, {4,5,6}};
-
char *p[3];
//p is array of 3 pointers to char.
示例:
char *juices[] = { "dragonfruit", "waterberry", "sharonfruit", "uglifruit",
"rumberry", "kiwifruit", "mulberry", "strawberry", "blueberry",
"blackberry", "starfruit" };
char *names_for_dog[] = {"Bowser", "Bonza", "Snodgrass"};
-
char p[][3];
//p is array of array of 3 char.
示例:
char tracks[][80] = { "I left my heart in Harvard Med School",
"Newark, Newark - a wonderful town", "Dancing with a Dork",
"From here to maternity", "The girl from Iwo Jima", };
-
int (*p)[3];
//p is pointer to array of 3 ints.
示例:
int data1[2][3] = { {1,2,3}, {4,5,6}};
int (*a2)[3] = data1;//pointer to int[3]
printf("%d %d\n" , a2[0][1], a2[1][2]);//2 6
-
char (*p)[3];
//p is pointer to array of 3 char.
例如: ************我需要一个很好的例子*****************
-
int *(p[3]); is equivalent to int *p[3];
//p is array of 3 pointers to int.
-
char *(p[3]); is equivalent to char *p[3];
//p is array of 3 pointers to char.
-
int (*p[8])[5];
//p is array of 8 pointers to array of 5 ints.
示例:
int data2[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
int (*a3[3])[4] = { &data2[0], &data2[1], &data2[2] };//array of pointer to int[4]
printf("%d %d %d\n" , (*a3[0])[2], (*a3[1])[0], (*a3[2])[3]);//3 5 12
-
char (*p[8])[5];
//p is array of 8 pointers to array of 5 char.
例如: ************我需要一个很好的例子*****************
-
int **p;
//p is pointer to pointer to int
例如: ************我需要一个很好的例子*****************
-
char **p;
//p is pointer to pointer to char
例如: ************我需要一个很好的例子*****************
答案 0 :(得分:1)
#include <stdio.h>
int main (void) {
int x = 1;
int y = 2;
int z = 3;
int *a1[3] = {&x, &y, &z};//array of pointer to int
printf("&x = %p, a1[0] = %p\n", &x, a1[0]);
printf("%d %d %d\n", *a1[0], *a1[1], *a1[2]);//1 2 3
int data1[2][3] = { {1,2,3}, {4,5,6}};
int (*a2)[3] = data1;//pointer to int[3]
printf("%d %d\n", a2[0][1], a2[1][2]);//2 6
int data2[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
int (*a3[3])[4] = { &data2[0], &data2[1], &data2[2] };//array of pointer to int[4]
printf("%d %d %d\n", (*a3[0])[2], (*a3[1])[0], (*a3[2])[3]);//3 5 12
return 0;
}