30天学会C语言: Day 27-指标当参数

函式没办法使用其他函式中的变数

#include <stdio.h>
#include <stdlib.h>

void fun(int x) {
    x = 100;
    printf("%d\n", x);
}

int main() {
    int x = 10;
    fun(x);
    printf("%d\n", x);

    return 0;
}

因为函式和函式间传递的是 ,其他的函式只能知道变数值而不知道变数的位置,所以 fun() 没办法改变 main() 的值

如果要让其他的函式更改变数的值,就需要以指标作为传递的资料
scanf() 的功能是改变变数值,所以丢给 scanf() 的变数要加上 &

指标参数

和宣告变数一样,在参数名称前加上 * 代表指标

#include <stdio.h>
#include <stdlib.h>

void fun(int *x) {
    *x = 100;
    printf("%p\n", x);
}


int main() {
    int x = 10;
    fun(&x);
	printf("%p\n", &x);

    return 0;
}

* 是取值运算子,可以取得指标指向的变数

#include <stdio.h>
#include <stdlib.h>

void fun(int *x) {
    printf("%d\n", *x);
}


int main() {
    int x = 10;
    fun(&x);

    return 0;
}

透过 * 可以指派其他函数中的变数

#include <stdio.h>
#include <stdlib.h>

void fun(int *x) {
    *x = 100;
    printf("%d\n", *x);
}

int main() {
    int x = 10;
    fun(&x);
    printf("%d\n", x);

    return 0;
}

fun() 执行後 main() 中的 x 被改成100


<<:  30天学会Python语言: Day 27-时间管理大师

>>:  Day 29 RSpec 里的 Factories 和 Fixtures

Day 07 JavaScript/Rails API

阿修的说文解字 API 的全名是 Application Programming Interface...

UNIX、BSD 与 Linux 的爱恨情仇

本文目标 熟悉 UNIX 作业系统的发展 认识自由软件运动与 GNU 计画 了解 C 语言是被设计来...

[DAY 02] IAM

IAM (Identity and Access Management) 对於 AWS 上的服务安全...

[13th-铁人赛]Day 5:Modern CSS 超详细新手攻略 - Selector (一)

今天再来深度研究一下CSS的语法!我要介绍的是CSS中的选择器,选择器是最重要的语法之一,决定了要改...

(Day 30) chequered flag

congrats to everyone who managed to finsih 30 days...