C++之数组

一维数组

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using namespace std;

int main() {
    system("chcp 65001");
    double a[10];
    cout << "-------------初始数组的值-------------" << endl;
    for (int i = 0; i < 10; ++i) {
        cout << a[i] << endl;
    }
    for (int i = 0; i < 10; i++) {
        a[i] = i + 100;
    }
    cout << "-------------重新赋值数组的值-------------" << endl;
    cout << "Element" << setw(13) << "Value" << endl;
    for (int i = 0; i < 10; ++i) {
        cout << i << setw(7) << setw(17) << a[i] << endl;
    }
    return 0;
}
输出:
Active code page: 65001
-------------初始数组的值-------------
3.91881e-317
6.95223e-310
3.95253e-323
0
2.07618e-317
1.97626e-322
0
0
3.95253e-323
2.07493e-317
-------------重新赋值数组的值-------------
Element        Value
0              100
1              101
2              102
3              103
4              104
5              105
6              106
7              107
8              108
9              109

二维数组

初始化二维数组:int b[3][2] = {{1, 2},
                   {3, 4},
                   {5, 6}};

使用指针指向数组

#include <iostream>

using namespace std;

int main() {
    system("chcp 65001");
    int c[5] = {10, 20, 30, 40, 50};
    int *p;
    //输出数组名表示的是首元素的地址,指针p指向数组的第一个地址,这里的c相当于&c[0]
    p = c;
    cout << "----------使用指针表示数组的值----------" << endl;
    for (int i = 0; i < 5; ++i) {
        cout << "*(p[" << i << "]):"
             << *(p + i) << endl;
    }
    cout << "------使用数组名作为地址输出数组的值------" << endl;
    for (int i = 0; i < 5; ++i) {
        cout << "*(c[" << i << "]):"
             << *(c + i) << endl;
    }
    return 0;
}
输出:
Active code page: 65001
----------使用指针表示数组的值----------
*(p[0]):10
*(p[1]):20
*(p[2]):30
*(p[3]):40
*(p[4]):50
------使用数组名作为地址输出数组的值------
*(c[0]):10
*(c[1]):20
*(c[2]):30
*(c[3]):40
*(c[4]):50

特殊的char类型数组

1.C++ 中,将 char * 或 char[] 传递给 cout 进行输出,结果会是整个字符串,如果想要获得字符串的地址(第一个字符的内存地址),可使用以下方法:
强制转化为其他指针(非 char*)。可以是 void ,int ,float , double * 等。 使用 &s[0] 不能输出 s[0](首字符)的地址。因为 &s[0] 将返回 char,对于 char(char 指针),cout 会将其作为字符串来处理,向下查找字符并输出直到字符结束 *。
2.C++ 对 char 型数组做了特殊规定,直接输出首地址时,会输出数组内容。如果想得到地址,可采用 & 。

#include <iostream>

using namespace std;
const int MAX = 3;

int main() {
    system("chcp 65001");
    char var[MAX] = {'a', 'b', 'c'};
    char *p;
    p = var;
    cout << "输出char数组首地址时直接输出数组元素:" << p << endl;
    for (int i = 0; i < MAX; ++i) {
        cout << "One way Address of var[" << i << "]=";
        //cout << &var + i << endl;(error)
        //&var[i]是char*类型,直接输出的是字符,需要强转成其他类型得到地址
        cout << (double *) &var[i] << endl;
        cout << "Another way Address of var[" << i << "]=";
        //转成其他类型的数组输出地址
        cout << (int *) p << endl;
        //指针下移
        cout << "输出数组的值var[" << i << "]=" << *p << endl;
        p++;
    }

    return 0;
}
输出:
Active code page: 65001
输出char数组首地址时直接输出数组元素:abc
One way Address of var[0]=0x63fe11
Another way Address of var[0]=0x63fe11
输出数组的值var[0]=a
One way Address of var[1]=0x63fe12
Another way Address of var[1]=0x63fe12
输出数组的值var[1]=b
One way Address of var[2]=0x63fe13
Another way Address of var[2]=0x63fe13
输出数组的值var[2]=c

函数传递数组参数

#include <iostream>
#include <cstdlib>

using namespace std;

//不带索引的数组名(指针)
void my_func(int *pre);

//传带索引的数组参数
void my_func1(int pre[10]);

//传带空索引的数组参数
void my_func2(int pre[]);

void my_func(int *pre) {
    cout << "通过不带索引的数组名传递一个指向数组的指针" << endl;
}

void my_func1(int pre[10]) {
    cout << "传递带索引的数组参数" << endl;
}

void my_func2(int pre[]) {
    cout << "传递索引为空的数组参数" << endl;
}

下面举个例子来体会一下

#include <iostream>

using namespace std;

//使用模板类
template<class T>
int get_array_length(T &array);

template<class T>
double get_average(T &arr, int size);

int main() {
    system("chcp 65001");
    int a[10] = {10, 20, 30, 40, 50, 60, 100, 200, 300, 3000};
    int array_length = get_array_length(a);
    double average = 0;
    average = get_average(a, array_length);
    cout << "数组的平均值:" << average << endl;
    return 0;
}

template<class T>
int get_array_length(T &array) {
    return sizeof(array) / sizeof(array[0]);
}

template<class T>
double get_average(T &arr, int size) {
    int sum = 0;
    double average = 0;
    for (int i = 0; i < size; ++i) {
        sum += arr[i];
    }
    average = double(sum) / size;
    return average;
}
Active code page: 65001
数组的平均值:381

动态获取数组长度

#include <iostream>
#include <cstdlib>

using namespace std;
const char NEWLINE = '\n';

template<class T>

int get_array_length(T &array);

int main() {
    system("chcp 65001");
    int a[10];
    int length = 0;
    length = get_array_length(a);
    cout << "数组长度:" << length << endl;
    return 0;
}

template<class T>
int get_array_length(T &array) {
    int array_length = sizeof(array) / sizeof(array[0]);
    return array_length;
}
输出:
Active code page: 65001
数组长度:10

指针占用内存

arr 是一个指针,即为地址,指针占几个字节跟语言无关,而是跟系统的寻址能力有关。
例如:以前是 16 位地址,指针即为 2 个字节,现在一般是 32 位系统,所以是 4 个字节,以后 64 位,则就占 8 个字节。
所以以上介绍的三种方式,获得的指针内存地址都是8个字节,但是如果是模板类,则按照捕获参数的数组类型动态分配,int:4,double:8等等。如果传入的是指针,则还是按照系统的寻址能力分配,也就是8.

#include <iostream>

using namespace std;

template<class T>
int get_array_length(T &array);

template<class T>
double get_average(T &arr, int size);

int main() {
    system("chcp 65001");
    int a[10] = {10, 20, 30, 40, 50, 60, 100, 200, 300, 3000};
    int *pre;
    pre = a;
    cout << "指针pre指向的地址:" << pre << endl << "数组a[0]内存地址:" << &a[0] << endl << "数组a内存地址:" << a << endl;
    int array_length = get_array_length(pre);
    double average = 0;

    average = get_average(pre, array_length);
    cout << "数组的平均值:" << average << endl;
    return 0;
}

template<class T>
int get_array_length(T &array) {
    cout << "模板类中指针参数的内存大小:" << sizeof(array) << endl
         << "模板类中数组第一个参数内存大小:" << sizeof(array[0]) << endl;
    return sizeof(array) / sizeof(array[0]);
}

template<class T>
double get_average(T &arr, int size) {
    int sum = 0;
    double average = 0;

    for (int i = 0; i < size; ++i) {
        sum += arr[i];
    }
    average = double(sum) / size;
    return average;
}
输出:
Active code page: 65001
指针pre指向的地址:0x63fde0
数组a[0]内存地址:0x63fde0
数组a内存地址:0x63fde0
模板类中指针参数的内存大小:8
模板类中数组第一个参数内存大小:4
数组的平均值:15

从函数返回数组

C++函数不能直接返回数组类型,但是数组是指针常量,可以定义指针返回类型来实现。

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

template<class T>
int *get_random(T &a);

template<class T>
int get_array_length(T &arr);

int main() {
    system("chcp 65001");
    int *p;
    int a[10];
    p = get_random(a);
    cout << "-------------------------------------" << endl;
    for (int i = 0; i < get_array_length(a); ++i) {
        cout << "指针指向的数组元素的值a[" << i << "]:" << *p << endl;
        p++;
    }
    return 0;
}

template<class T>
int *get_random(T &a) {
    cout << a << endl;
    int size = get_array_length(a);
    cout << size << endl;
    srand(unsigned(time(NULL)));

    for (int i = 0; i < size; ++i) {
        a[i] = rand();
        cout << "重新赋值数组元素的值a[" << i << "]:" << a[i] << endl;
    }
    return a;
}

template<class T>
int get_array_length(T &arr) {
    return sizeof(arr) / sizeof(arr[0]);
}
输出:
Active code page: 65001
0x63fde0
10
重新赋值数组元素的值a[0]:24281
重新赋值数组元素的值a[1]:12052
重新赋值数组元素的值a[2]:1185
重新赋值数组元素的值a[3]:1198
重新赋值数组元素的值a[4]:18454
重新赋值数组元素的值a[5]:8739
重新赋值数组元素的值a[6]:6754
重新赋值数组元素的值a[7]:1249
重新赋值数组元素的值a[8]:22626
重新赋值数组元素的值a[9]:16085
-------------------------------------
指针指向的数组元素的值a[0]:24281
指针指向的数组元素的值a[1]:12052
指针指向的数组元素的值a[2]:1185
指针指向的数组元素的值a[3]:1198
指针指向的数组元素的值a[4]:18454
指针指向的数组元素的值a[5]:8739
指针指向的数组元素的值a[6]:6754
指针指向的数组元素的值a[7]:1249
指针指向的数组元素的值a[8]:22626
指针指向的数组元素的值a[9]:16085

1、在循环外面调用srand((unsigned)time(NULL));函数后,函数的参数做为初始种子seed,rand()函数利用初始种子将返回值next做为新的“种子”,保证每次"种子"都不同;
2、假如srand函数放在循环体内部,由于time函数只精确到s,srand函数的参数(初始种子seed)在1s之内不会发生变化,rand()函数利用初始种子生成的返回值next(做为新的“种子”)每次都一样,所以需要放在循环体外面。

#include <iostream>

using namespace std;

float *mul_matrix(float m[4], float a[4], float b[4]);

int main() {
    float a[4] = {1.75, 0.66, 0, 1.75};
    float b[4] = {1, 1, 0, 0};
    // 开辟一个float数组(4个元素)空间,返回首元素的地址
    float *m;
    m = new float[4];
    float *M;
    M = mul_matrix(m, a, b);
    cout << M[0] << endl
         << M[1] << endl
         << M[2] << endl
         << M[3] << endl;
    //释放手动分配的内存,也可以使用free()来释放
    delete[]m;
    //free(m);
    return 0;
}

float *mul_matrix(float m[4], float a[4], float b[4]) {
    m[0] = a[0] * b[0] + a[1] * b[2];
    m[1] = a[0] * b[1] + a[1] * b[3];
    m[2] = a[2] * b[0] + a[3] * b[2];
    m[3] = a[2] * b[1] + a[3] * b[3];
    return m;
}
输出:
1.75
1.75
0
0

1.数组的 delete 是 delete[]。
2.C++ 里面手动内存分配的一个重要原则是谁分配谁释放。所以,不应该在MultMatrix里new数组,而应该在外面new好了之后传进去修改。
3.要想返回一个数组,使用智能指针之类的东西才是正途。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值