我必须在我的程序中使用动态长度int数组,并希望能够在我的代码中的不同点获取其中的对象数.我对C++并不熟悉,但这就是我所拥有的.为什么它没给我合适的长度?谢谢.
<#include <iostream>
Using Namespace std;
int length(int*);
void main()
{
int temp[0];
temp[0] = 7;
temp [1] = 10;
temp[2] = '\0';
cout << length(temp) << endl;
}
int length(int* temp)
{
int i = 0;
int count = 0;
while (*temp + i != '\0')
{
count++;
i++;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
目前它只是进入无限循环; _;
Pet*_*ham 15
在C++中,数组不是动态的.您的临时数组的长度为零,并且尝试写入超出其长度的成员是未定义的行为.它很可能不起作用,因为它将写入堆栈的某些部分.
创建一个固定大小的数组,其中有足够的空间放置您想要的所有内容,或者使用std::vector<int>哪个是动态数据结构.
#include <iostream>
#include <vector>
using namespace std;
int length(int*);
int main () // error: ‘::main’ must return ‘int’
{
int temp[3];
temp[0] = 7;
temp[1] = 10;
// don't use char constants for int values without reason
temp[2] = 0;
cout << length(temp) << endl;
vector<int> vec_temp;
vec_temp.push_back(7);
vec_temp.push_back(10);
cout << vec_temp.size() << endl;
}
int length(int* temp)
{
int i = 0;
int count = 0;
while (*(temp + i) != 0) // *temp + i == (*temp) + i
{
count++;
i++; // don't really need both i and count
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
对于向量,不需要在开始时指定大小,并且可以放入零,并且查找长度是一个简单的操作而不是需要循环.
循环中的另一个错误是你正在查看数组的第一个成员并将i添加到该值,而不是通过i递增指针.你真的不需要我和计数,所以可以写几个其他的方式,或者直接递增temp:
int length(int* temp)
{
int count = 0;
while (*temp != 0)
{
++count;
++temp;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
或使用count来索引temp:
int length(int* temp)
{
int count = 0;
while (temp[count] != 0)
++count;
return count;
}
Run Code Online (Sandbox Code Playgroud)
出于几个原因,这种方法是一个坏主意,但首先是一些问题:
int temp[0];
Run Code Online (Sandbox Code Playgroud)
这是一个包含0个项目的数组,我甚至认为它不允许用于堆栈元素.声明这样的数组时,必须指定您将使用的最大值数:例如int temp[10];
这非常重要! - 如果你指定的数字较少(例如[10]并且你使用[11])那么你将导致内存覆盖,最好崩溃,最坏的情况是导致奇怪的错误,这是追踪的噩梦.
下一个问题是这一行:
while (*temp + i != '\0')
Run Code Online (Sandbox Code Playgroud)
该行的作用是将值存储在'temp'指定的地址中并添加i.你想要的是获取temp指定的地址的第n个元素的值,如下所示:
while (*(temp + i) != '\0')
Run Code Online (Sandbox Code Playgroud)
这就是错误的,但你应该花五分钟时间思考一个更好的方法来做到这一点.
我提到它的原因是一个坏主意是:
相反,我建议你维护一个单独的值来存储数组中的元素数量.一种非常常见的方法是创建一个包含这个概念的类(一个元素块和当前大小).
C++标准库附带了一个名为"vector"的模板类,可用于此目的.它与数组不完全相同(您必须在编制索引之前先添加项目),但它非常相似.它还支持复制/调整大小,这也很方便.
这是你编写的程序使用std :: vector.而不是'长度'功能,我添加了一些东西来打印出值:
#include <vector>
#include <iostream>
void print(std::vector<int> const& vec)
{
using namespace std;
for (size_t i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
cout << endl;
}
int main()
{
std::vector<int> temp;
temp.push_back(7);
temp.push_back(10);
print(temp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)