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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)