Converting an array of digits to an integer

Hello, I’m trying to read using serial communication and use a value as an int,
so what I tried to do is place the incoming digits in an array of ints and turn the int array into one single number.
I tried to do that and I have realized that the algorithm is very simple but it didn’t work using the Arduino.
there is what I’ve tried.

int GetNum(int arr[]) {

  int sum = 0;

  for (int i = 0; i < sizeof(arr); i++) {

    if (arr[i] != -99) { // represents a blank digit (the algorithm ingonrs that)
      sum += arr[i] * pow(10, (sizeof(arr) - i));
    }

  }
  return sum;
}

I tried it with a debugging table and it worked, for some reason, it doesn’t work even when I try to print the function with predefined values in an array, I might have done something wrong with the algorithm because I’m pretty new to C++ I’m coming from the world of C#.

int GetNum(int arr[]) {

is the same as:

int GetNum(int *arr) {

The sizeof(int *) is 2 (bytes).

gfvalvo:

int GetNum(int arr[]) {

is the same as:

int GetNum(int *arr) {

The sizeof(int *) is 2 (bytes).

what do you mean? I just want to find out the size of the array how do I do that?

dindibo4: what do you mean?

I mean that a pointer to an int has a size of 2 bytes. Perhaps 4 bytes on a 32-bit machine.

dindibo4: I just want to find out the size of the array how do I do that?

Easiest way to tell the GetNum() function the size of the array is to pass it as a second parameter.

Also your conversion algorithm is horribly inefficient. This would be much better:

sum = 10 * sum + arr[i];

Another inefficiency is your use of an int array to hold a string of digits. A byte array would work.

gfvalvo: I mean that a pointer to an int has a size of 2 bytes. Perhaps 4 bytes on a 32-bit machine. Easiest way to tell the GetNum() function the size of the array is to pass it as a second parameter.

Also your conversion algorithm is horribly inefficient. This would be much better:

sum = 10 * sum + arr[i];

thanks for the algorithm and by the way that's a good suggestion to use byte instead of int I'll change that, but can you tell me again how to determine what is the length of the array? as I said I'm used to C# not c++

Probably a couple ways to handle it. As I said, the simplest is to pass the size as a second parameter:

In the Calling function:

GetNum(theArray, sizeof(theArray) / sizeof(theArray[0]));

In the GetNum function:

GetNum(byte arr[], int arraySize) {


}

gfvalvo: Probably a couple ways to handle it. As I said, the simplest is to pass the size as a second parameter:

In the Calling function:

GetNum(theArray, sizeof(theArray) / sizeof(theArray[0]));

In the GetNum function:

GetNum(byte arr[], int arraySize) {

}

You are passing the number of elements, not the size (admitted for byte arrays the numbers are the same).

Yes, number of elements is what OP needs in the GetNum() function. I should have called the parameter numElements.