C++学习笔记总结练习:数组参数

59 篇文章 1 订阅
35 篇文章 0 订阅

数组参数

在 C++ 中,可以通过数组参数来传递数组给函数。这意味着你可以将一个数组作为函数的参数,以便在函数内部对数组进行操作或访问。

理解 C++ 中的数组参数涉及以下几个方面:

语法:在函数声明或定义中,可以使用数组类型作为参数类型。例如,void myFunction(int arr[]) 或 void myFunction(int arr[5])。这里的 arr 是一个形式参数,表示一个整数数组。

传递数组:当你调用带有数组参数的函数时,你可以传递一个数组作为实际参数。例如,int myArray[5] = {1, 2, 3, 4, 5}; myFunction(myArray);。在函数调用中,myArray 是一个实际参数,表示一个整数数组。

数组大小:在函数中,你可以使用数组参数来访问数组元素,并使用数组大小来遍历数组。在函数声明中,可以指定数组参数的大小,也可以省略大小。然而,在 C++ 中,数组参数的大小信息在函数内部是不可用的,因此通常需要额外的参数来传递数组的大小。

数组指针:在函数中,数组参数实际上是一个指向数组首元素的指针。因此,你可以使用指针算术或下标运算符来访问数组元素。例如,arr[0] 或 *(arr + 1)。

下面是一个示例函数,演示如何使用数组参数:

#include <iostream>

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

int main() {
    int myArray[] = {1, 2, 3, 4, 5};
    int size = sizeof(myArray) / sizeof(myArray[0]);
    printArray(myArray, size);
    return 0;
}

在这个示例中,printArray 函数接受一个整数数组 arr 和一个整数 size 作为参数。函数使用循环遍历数组,并打印每个元素。在 main 函数中,我们定义了一个整数数组 myArray,并计算数组的大小。然后,我们调用 printArray 函数,传递 myArray 和大小作为参数。

当你运行这个程序时,它会打印出数组的所有元素。

三种形式

void test1(int *s)
void test2(int s[])
void test3(int s[5])

实例

#include <iostream>
#include <vector>
using namespace std;

// 测试字符串和字符数组的参数传递
void test1(int *s){
    cout<<*(s)<<endl;
    return;
}
void test2(int s[]){
    cout<<*s<<endl;
    return;
}
void test3(int s[5]){
    cout<<*s<<endl;
    return;
}

int main()
{
    int s1[]={1,2,3,4,5,6,7,8};
    int s2[3]={4,5,6};
    int* s3 = new int(999);
    test1(s3);
    test2(s3);
    test3(s3);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mDeepLearning4205

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值