posts - 137,comments - 0,views - 40595

1.一个指针在32位操作系统上占4个字节,在64位操作系统上占8个字节,但是,编译器为了兼容32位操作系统和64位操作系统,所以指针都是4个字节长度。

下面程序中的形参本质上是一个指针,所以无论定义了几个参数都只能传递四个字节。

复制代码
#include <iostream>
#include <windows.h>
using namespace std;

void scorePrint(int score[6]) {    //形参
    cout << sizeof(score) << endl;
}
int main() {
    int score[6] = { 60,70,80,90,100,20 };
    cout << sizeof(score) << endl;

    scorePrint(score);

    system("pause");
    return 0;
}
复制代码

 2.若使用数组作为函数的参数,就可解决这个参数传递的问题。

复制代码
#include <iostream>
#include <windows.h>
using namespace std;

void scorePrint(int score[], int n) {   //n为数组元素的个数
    for (int i = 0; i < n; i++) {
        cout << "" << i + 1 << "门课程的成绩:" << score[i] << endl;
    }
}
int main() {
    int score[6] = { 60,70,80,90,100,120 };
    cout << sizeof(score) << endl;

    scorePrint(score,6);
    system("pause");
    return 0;
}
复制代码

 3.当数组作为函数的参数时,数组的值可以被修改:

复制代码
#include <iostream>
#include <windows.h>
using namespace std;

void scorePrint(int score[], int n) {
    for (int i = 0; i < n; i++) {
        cout << "" << i + 1 << "门课程的成绩:" << score[i] << endl;
    }
}
//把每门课程的成绩加val分
void scoreAdd(int score[], int n, int val) {
    for (int i = 0; i < n; i++) {
        score[i] += val;
    }
}
int main() {
    int score[6] = { 60,70,80,90,100,120 };
    scorePrint(score,6);  //打印加分前的成绩
    cout << endl;
    scoreAdd(score,6,10);  //把每门课程的成绩加10分
    scorePrint(score, 6);  //打印加分后的成绩

    system("pause");
    return 0;
}
复制代码

 

 4.若只是普通的传参,而不用数组或指针作为函数的参数,则数组里的值无法被修改:

复制代码
#include <iostream>
#include <windows.h>
using namespace std;

void addSalary(int salary, int add) {
    salary += add;
    cout << "加薪中:" << salary << endl;
}
int main() {
    int x = 20000;
    cout << "加薪前:" << x << endl;

    addSalary(x,5000);

    cout << "加薪后:" << x << endl; //加薪后的值x没有改变

    system("pause");
    return 0;
}
复制代码

posted on   wshidaboss  阅读(3035)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示