C语言指针注解

C语言指针注解

C语言指针实例

指针的类型可以是int,double,float,struct …. 决定指针内部存放的数据大小,
如果定义的是一个数组,类型可以让编译器 在p++是跳多少个大小的地址

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdlib.h>  
#include <stdio.h>

void main(){
double array[5] = {1,2,3,4,5} ;
int i ;
// double *p = &array[0] ;//跟下面等价
double *p = array ; //表示一个double的指针, 初始化指向array的首地址
for (i=0;i<5;i++){
printf("@%p array[%d]=%f,%p\n",&array[i],i,*p,p) ; //取值 *p
p++; //p++ 会按照double 8个字节来增加,编译器会帮你自动搞定
}
}

结构体指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Books {  //总共占256个字节,16进制就是0x100个字节
char title[50];
char author[50];
char subject[152];
int book_id;
};

void main(){
struct Books booklist[5] ;
int i ;
struct Books *p = booklist ; //表示一个占Books struct的指针
for (i=0;i<5;i++){
printf("@%p booklist[%d] @%p\n",&booklist[i],i,p) ; //
p++; //p++ 会按照0x100(256字节)来增加
}
}
执行`gcc main.c; ./a.exe`:
@0x28c768 booklist[0] @0x28c768
@0x28c868 booklist[1] @0x28c868
@0x28c968 booklist[2] @0x28c968
@0x28ca68 booklist[3] @0x28ca68
@0x28cb68 booklist[4] @0x28cb68

结构体指针元素访问

可以用结构体来定义指针类型

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
#include <stdlib.h>  
#include <stdio.h>
#include <string.h>

struct Books { //总共占256个字节,16进制就是0x100个字节
char title[50];
char author[50];
char subject[152];
int book_id;
};

void main(){
struct Books booklist[5] ;
int i ;
struct Books *p = booklist ; //表示一个占Books struct的指针
for (i=0;i<5;i++){
//对于结构体指针,访问元素时用 p->title 访问 ,一般结构体直接用book.title 访问
strcpy( p->title, "C Programming");
strcpy( p->author, "Nuha Ali");
strcpy( p->subject, "C Programming Tutorial");
p->book_id = 100+i;
printf("@%p booklist[%d] @%p\n",&booklist[i],i,p) ; //
p++; //p++ 会按照0x100(256字节)来增加
}
p = booklist ;
for (i=0;i<5;i++){
printf("BookID:%d\nTitle:%s\nAuthor:%s\nSubject:%s\n",\
booklist[i].book_id,booklist[i].title,booklist[i].author,booklist[i].subject);
// printf("BookID:%d\nTitle:%s\nAuthor:%s\nSubject:%s\n",p->book_id,p->title,p->author,p->subject);//也是可以的
printf("--------------------------------------------\n");
p++;
}
}

结构体指针访问元素用 ‘->’ ,即 ‘p->tilte’
一般结构体访问元素就用‘.’ ,即 ‘book.title’

union 共用体

union共用体可以方便复用资源,有点像高级程序里面的泛型

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
#include <stdio.h>
#include <string.h>

union Data
{
int i;
float f;
char str[20];
};

int main()
{
union Data data;
union Data *p;
p = &data ;

printf( "Memory size occupied by data : %d\n", sizeof(data));
data.i = 32 ;
printf( "data.i : %d\n", data.i);
data.f = 32.12 ;
printf( "data.f : %f\n", data.i);
strcpy(data.str,"hello world") ;
printf( "data.str : %s\n", data.str);
printf( "data.str : %s\n", p->i);
printf( "data.str : %s\n", p->f);
printf( "data.str : %s\n", p->str);
return 0;
}

评论