0%

初识C语言(四)

文章时效性提示

本文发布于 525 天前,部分信息可能已经改变,请注意甄别。

指针

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main() {
    int a = 10;//向内存申请了4个字节的空间
    int* p = &a;//p是一个变量-是指针变量(用来存地址的)-类型是int型
    printf("%p\n",&a);//%p是用来打印地址的,&a是用来取a的地址的。
    printf("%p\n",p);//打印的内容和上面是一样的
    *p = 20;//* - 解引用操作符(间接访问操作符)
    printf("a = %d\n",a);//改变了a的值,a = 20
    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);//结果是5.500000
    printf("%lf\n",*pd);//结果和直接打印d是一样的
    printf("%d\n",sizeof(pd));//打印的结果是4或8,主要取决于平台是32位或64位
    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*));//打印的结果都是4或8,主要取决于平台是32位或64位
    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>
//创建一个结构体类型Book
struct Book
{
    char name[20];//C语言程序设计
  short price;//价格是55
};//此分号用于结束类型定义

int main()
{
    //利用结构体类型-创建一个该类型的变量b1
    struct Book b1 = {"C语言程序设计",55};
    printf("书名:%s\n",b1.name);
    printf("价格:%d元\n",b1.price);//打印信息
    b1.price = 15;
    strcpy(b1.name,"C++"); //strcpy-string copy - 字符串拷贝 - 库函数string.h
    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;
    //利用pb打印出书名和价格
//    printf("%s\n",(*_pb).name);
//    printf("%d\n",(_*pb).price);
    printf("%s\n",pb->name);
    printf("%d\n",pb->price);//使用箭头->和上面的点.操作符是一样的
    //.  结构体变量.成员
    //-> 结构体指针->成员
    return 0;
}