zoukankan      html  css  js  c++  java
  • 【C语言】指针到底有什么用

    指针到底有什么用?只是多了一种访问变量的方法而已,有这么重要吗?

    1. 通过函数修改形参的值(例子:交换两个形参的值)

    错误写法

    #include <stdio.h>
    void MySwap(int a, int b) {
    	int temp = a;
    	a = b;
    	b = temp;
    }
    int main(void) {
    	int a=1, b=2;
    	MySwap(a, b);
    	printf("%d, %d
    ", a, b);
    	return 0;
    }
    

    输出结果

    1, 2
    

    交换失败。因为MySwap()函数中的参数是局部变量,和main()函数中的变量没有任何关系。

    正确写法

    #include <stdio.h>
    void MySwap(int* pa, int* pb) {
    	int temp = *pa;
    	*pa = *pb;
    	*pb = temp;
    }
    int main(void) {
    	int a=1, b=2;
    	MySwap(&a, &b);
    	printf("%d, %d
    ", a, b);
    	return 0;
    }
    

    输出结果

    2, 1
    

    交换成功。因为MySwap()函数的参数是指针,可以通过指针直接修改内存上的数据。

    所以,函数中将指针作为参数可以直接修改主调函数中变量的值。

    2. 将结构体作为函数参数(例子:输出学生信息)

    不合适的写法

    #include <stdio.h>
    typedef struct Student {
    	char *name;
    	int age;
    	int score;
    } Student;
    void Say(Student stu) {
    	printf("我是%s,年龄是%d,成绩是%d
    ", stu.name, stu.age, stu.score);
    }
    int main(void) {
    	Student stu;
    	stu.name = "小明";
    	stu.age = 10;
    	stu.score = 90;
    	printf("sizeof(stu)=%d
    ", sizeof(stu));
    	Say(stu);
    	return 0;
    }
    

    输出结果

    sizeof(stu)=12
    我是小明,年龄是10,成绩是90
    

    stu结构体变量占用了12个字节,在调用函数时,需要原封不动地将12个字节传递给形参。如果结构体成员很多,传送的时间和空间开销就会很大,影响运行效率。

    正确写法

    #include <stdio.h>
    typedef struct Student {
    	char *name;
    	int age;
    	int score;
    } Student;
    void Say(Student *stu) {
    	printf("我是%s,年龄是%d,成绩是%d
    ", stu->name, stu->age, stu->score);
    }
    int main(void) {
    	Student stu;
    	stu.name = "小明";
    	stu.age = 10;
    	stu.score = 90;
    	printf("sizeof(&stu)=%d
    ", sizeof(&stu));
    	Say(&stu);
    	return 0;
    }
    

    输出结果

    sizeof(&stu)=12
    我是小明,年龄是10,成绩是90
    

    可见,使用结构体指针的空间开销比直接使用结构体变量要少,当结构体的成员很多时,还可以减少时间开销,提高运行效率。

    所以,使用指针可以减少空间和时间开销。

  • 相关阅读:
    .Net 开源项目资源大全
    无法向会话状态服务器发出会话状态请求
    网站限制不能点击右键
    ashx页面中context.Session["xxx"]获取不到值的解决办法
    SQL Server 2008 错误 233 的解决办法
    Best MVC Practices 最佳的MVC实践
    char* 转换成 CString
    MFC圆角背景移动边角底色毛刺解决方案
    CString转换为const char*
    分享一份安卓开发包,集成开发环境
  • 原文地址:https://www.cnblogs.com/HuZhixiang/p/12932494.html
Copyright © 2011-2022 走看看