gpt4 book ai didi

c++ - 尝试使变量检查数组中的内容

转载 作者:行者123 更新时间:2023-12-02 10:05:27 24 4
gpt4 key购买 nike

这是我的功能

bool ft_numchecksingle(string user_num, int arr[])
{
bool check = false;
int mynum = stoi(user_num.substr(2, -1));
int len = sizeof(arr) / sizeof(arr[0]);
for (int x = 0; x <= len; x++)
{
if (mynum == arr[x])
check = true;
}
return (check);
}

这是数组
    int arr[] = { 213, 220, 560, 890 };

如果我在该数组中输入任何内容,它应该返回true;但是,如果我输入560或890,则它总是返回false。

最佳答案

您不能根据给函数的参数确定数组的大小,因为array参数将为decay to a pointer

因此,在ft_numchecksingle函数中,以下行:

int len = sizeof(arr) / sizeof(arr[0]);

将给int的指针的大小(在您的平台上大概为8个字节)分配给 len除以 int的大小(大概为4个字节); (在您的情况下)这将是 2值,这就是为什么您的函数仅搜索数组的前两个元素。 [实际上,考虑到我在下面的“编辑”中提出的观点,指针很可能只有4个字节,因此,根据您的情况,“len”值为 1-然后,您将仅检查前两个元素,因为您的 x <= len循环中有 for!]

因为您的代码是 C++,所以您应该使用 std::vector container class,而不是“raw”数组;然后,您可以使用该类的 .size()成员来确定“数组”的大小。

另外,如果您确实必须使用原始数组类型,则需要将该数组的大小作为附加参数添加到函数中,如下所示:

bool ft_numchecksingle(string user_num, int arr[], size_t len)

然后,在 main(或从何处调用该函数)中,您可以使用如下代码:

int arr[] = { 213, 220, 560, 890 };
//...
bool test = ft_numchecksingle("560", arr, sizeof(arr) / sizeof(arr[0]));
//...

(请注意,此处编译器可以正确计算 sizeof(arr)值!)

编辑:作为重要的一点,并假设您在 len变量中具有数组的实际大小,则该数组的最后一个元素将具有索引 len - 1(不是 len)。因此,您的 for循环应为:

for (int x = 0; x < len; x++) 

而不是:

for (int x = 0; x <= len; x++) // When "x" EQUALS "len" you will be out-of-bounds!

关于c++ - 尝试使变量检查数组中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60411767/

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