数组元素的数目

Number of array elements

本文关键字:数组元素      更新时间:2023-10-16

我有一个小程序。

我想要得到数组p1的元素数量。调试时,我得到0。但我认为应该是6。

// ConsoleApplication3.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
using namespace std;
double array_concat(double p1[], double p2[])
{
    double ans[2][6];
    int i, j;
    i = 0;
    printf("%dn", sizeof(p1) / sizeof(p1[0])); //is this wrong?
    for (j = 0; j < sizeof(p1) / sizeof(p1[0]); j++){
        ans[i][j] = p1[j];
    }
    i = 1;
    for (j = 0; j < sizeof(p1) / sizeof(p1[0]); j++){
        ans[i][j] = p2[j];
    }
    return ans[2][6];
}

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hellon";
    int i;
    double c[2][6];
    double p1[6] = { 0, 1, 0, 0, 0, 0 };
    double p2[6] = { 1, 1, 0, 0, 0, 0 };
    c[2][6] = array_concat(p1, p2);
    for (i = 0; i < 12; i++){
        printf("%lfn", c[i]); //is this wrong?
    }
    return 0;
}

怎么了?

经过编辑的代码,因此p1、p2和函数的返回值最好是poiters。我按照例子做的https://www.kompf.de/cplus/artikel/funcpar.html,但不知怎么的,它不起作用。//ConsoleApplication3.cpp:确定Konsolenanwendung。//

    #include "stdafx.h"
    #include <iostream>
    #include <stdio.h>
    using namespace std;
    double **array_concat(double *p1, double *p2)
    {
    double** ans = 0;
    //ans = new double*[2];
        //double ans[2][6];
        int i, j;
        i = 0;
        printf("%dn", sizeof(p1) / sizeof(p1[0])); //is this wrong?
        for (j = 0; j < sizeof(p1) / sizeof(p1[0]); j++){
            ans[i][j] = p1[j];
        }
        i = 1;
        for (j = 0; j < sizeof(p1) / sizeof(p1[0]); j++){
            ans[i][j] = p2[j];
        }
        return ans;
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
        cout << "Hellon";
        int i;
        //double c[2][6];
        double p1[6] = { 0, 1, 0, 0, 0, 0 };
        double p2[6] = { 1, 1, 0, 0, 0, 0 };
        //double *c;
        double **c = array_concat(p1, p2);
        for (i = 0; i < 12; i++){
            printf("%lfn", c[i]); //is this wrong?
        }
        return 0;
    }

array_concat()中,p1是指针,而不是数组。数组不是C中的一流数据类型,不能作为函数参数传递;相反,它们"衰减"为指针。

数组参数语法具有误导性,在大多数情况下应该避免,以避免混淆。