gpt4 book ai didi

c++ - 整数数组长度 C++

转载 作者:太空狗 更新时间:2023-10-29 23:21:17 27 4
gpt4 key购买 nike

我必须在我的程序中使用动态长度 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;
}

目前它只是进入了一个无限循环;_;

最佳答案

在 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;
}

对于vector,一开始就不需要指定大小,可以填入0,求长度是一个简单的操作,不需要循环。

循环中的另一个错误是您正在查看数组的第一个成员并将 i 添加到该值,而不是将指针递增 i。你实际上并不需要 i 和 count,所以可以用其他几种方式编写,要么直接增加 temp:

int length(int* temp)
{
int count = 0;

while (*temp != 0)
{
++count;
++temp;
}

return count;
}

或使用计数来索引温度:

int length(int* temp)
{
int count = 0;

while (temp[count] != 0)
++count;

return count;
}

关于c++ - 整数数组长度 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683838/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com