数组元素的数目
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中的一流数据类型,不能作为函数参数传递;相反,它们"衰减"为指针。
数组参数语法具有误导性,在大多数情况下应该避免,以避免混淆。
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int