使用for循环和指针打印浮点数组

Printing float array using for loop and pointers

本文关键字:数组 打印 指针 for 循环 使用      更新时间:2023-10-16

我开始在数组和指针的CPP。

我试图打印一个浮点数数组,但是我超出了浮点数数组。

我怎么能停止打印浮点数组一旦我击中结束?

// all about arrays and pointers
#include <iostream>
using namespace std;
int main (int argc, char * argv []) {
    float inputs1 [] = { 12 };
    float inputs2 [] = { 12 , 4 };
    cout << "sizeof(inputs1)" << sizeof(inputs1) << endl;
    cout << "sizeof(inputs2)" << sizeof(inputs2) << endl;
    float *it = inputs2;
    cout << *it << endl;
    it++;
    cout << *it << endl;
    cout << endl;
    cout << "sizeof(inputs1): " << sizeof(inputs1) << endl;
    cout << "sizeof(inputs2): " << sizeof(inputs2) << endl;
    cout << "start address: " << &inputs2 << endl;
    cout << "end address: " << &inputs2[sizeof(inputs2)] << endl;
    for (float *it2 = inputs2; it2!=&inputs2[sizeof(inputs2)]; it2++) {
        cout << "it2 " << it2 << endl;
        cout << "*it2 " << *it2 << endl;
    }
}

sizeof返回其参数的大小(以字节为单位) - 不是其中的元素数1

要得到元素的数量,你必须用sizeof(inputs1)除以sizeof(inputs1[0])

1除非每个元素是一个字节,例如char