数组元素的数量

时间:2016-05-11 11:55:37

标签: c++ sizeof

我有一个小程序。

我想获得数组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("%d\n", 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 << "Hello\n";
    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("%lf\n", c[i]); //is this wrong?
    }

    return 0;
}

出了什么问题?

编辑代码,所以p1,p2和函数的返回值最好是poiters。我在示例https://www.kompf.de/cplus/artikel/funcpar.html中创建它,但不知何故它不起作用。             // ConsoleApplication3.cpp:Definiert denEinstiegspunktfürdieKonsolenanwendung。         //

    #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("%d\n", 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 << "Hello\n";
        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("%lf\n", c[i]); //is this wrong?
        }

        return 0;
    }

1 个答案:

答案 0 :(得分:3)

array_concat() p1中是指针,而不是数组。数组不是C中的第一类数据类型,不能作为函数参数传递;相反,他们“衰退”到指针。

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