Noodlez
Noodlez

Reputation: 53

Trying to make a variable check something inside an array

Here is my function

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

Here is the Array

    int arr[] = { 213, 220, 560, 890 };

It should return true if I enter anything within that array, however, if I enter 560 or 890 it always returns false.

Upvotes: 1

Views: 47

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51915

You can't determine the size of an array from an argument given to a function, as the array parameter will decay to a pointer.

So, in your ft_numchecksingle function, the following line:

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

will assign to len the size of a pointer-to-int (presumably, 8 bytes, on your platform) divided by the size of an int (presumably, 4 bytes); this will (in your case) be the value 2, which is why your function is only searching the first two elements of the array. [Actually, when considering the point I made in the "EDIT" below, it is more likely that the pointer is only 4 bytes, so the 'len' value is 1 in your case - you will then check only the first two elements, as you have x <= len in your for loop!]

As your code is C++, you should be using the std::vector container class, instead of a 'raw' array; you can then use the .size() member of that class to determine to the size of the 'array'.

Alternatively, if you really must use a raw array type, then you will need to add that array's size as an extra parameter to your function, as follows:

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

And then, in your main (or wherever you call that function from), you can use code like this:

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

(Note that, here, the compiler can correctly calculate the sizeof(arr) value!)

EDIT: As an important aside, and assuming you have the actual size of the array in the len variable, then the last element of that array will have the index len - 1 (not len). So, your for loop should be:

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

rather than:

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

Upvotes: 2

Related Questions