文章时效性提示
本文发布于 525 天前,部分信息可能已经改变,请注意甄别。
指针
1 2 3 4 5 6 7 8 9 10
| #include <stdio.h> int main() { int a = 10; int* p = &a; printf("%p\n",&a); printf("%p\n",p); *p = 20; printf("a = %d\n",a); return 0; }
|
1 2 3 4 5 6 7 8 9 10 11
| #include <stdio.h> int main() { double d = 3.14; double* pd = &d; *pd = 5.5; printf("%lf\n",d); printf("%lf\n",*pd); printf("%d\n",sizeof(pd)); return 0; }
|
指针变量的大小
1 2 3 4 5 6 7 8
| int main() { printf("%d\n",sizeof(char*)); printf("%d\n",sizeof(short*)); printf("%d\n",sizeof(int*)); printf("%d\n",sizeof(double*)); return 0; }
|
指针变量的大小是4或8字节,主要取决于32位平台(4字节)或64位平台(8字节)
结构体
想描述一个复杂对象,需要使用结构体,结构体就是自己创造出来的一种类型。
例如想创造一本书,需要书名、作者、出版社、定价等信息。
struct关键字-struct Book。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include <stdio.h> #include <string.h>
struct Book { char name[20]; short price; };
int main() { struct Book b1 = {"C语言程序设计",55}; printf("书名:%s\n",b1.name); printf("价格:%d元\n",b1.price); b1.price = 15; strcpy(b1.name,"C++"); printf("修改后书名:%s\n",b1.name); printf("修改后的价格:%d元\n",b1.price); return 0; }
|
结构体中想要修改数组内容,需要用到字符串拷贝函数 - strcpy。
strcpy(b1.name,"C++");的意思是把结构体b1中的name改成C++。
要使用strcpy,需要string.h库函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <stdio.h> int main() { struct Book b1 = {"C语言程序设计",55}; struct Book* pb = &b1;
printf("%s\n",pb->name); printf("%d\n",pb->price); return 0; }
|