下标到指针之间和转换
以下的程序做了什么。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <stdio.h> int main() { int a[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; int i = 0; int j = 0; for (i = 0; i<3; i++) { for (j=0; j<3; j++) { printf ( "%d\n" , *(*(a+i)+j)); } } } |
打印了数组中的每个元素:
指向指针的指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <stdio.h> int main() { int a = 1; int * p = NULL; int ** pp = NULL; pp = &p; *pp = &a; // ==> p = &a; printf ( "%d" , **pp); return 0; } |
使用实例:重置动态空间大小(类似于在函数中修改入参)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
#include <stdio.h> int reset( char **p, int size, int new_size) { int ret = 1; int i = 0; int len = 0; char * pt = NULL; char * tmp = NULL; char * pp = *p; if ( (p != NULL) && (new_size > 0)) { pt = ( char *) malloc (new_size); tmp = pt; len = (size < new_size) ? size : new_size; for ( i=0; i<len; i++) { *tmp++ = *pp++; } free (*p); *p = pt; } return ret; } int main() { char * p = ( char *) malloc (5); printf ( "%0X\n" , p); if ( reset(&p, 5, 3) ) { printf ( "%0X\n" , p); } return 0; |