vendredi 28 février 2020

Custom strtoi function compile time issue

I am trying to implement a very simple strtoi function. It works fine when when the passed arguments are dynamically created (case 2 below). However if the char is created by char[] which is allocated during compile time, I get a constant value on len because of std::strlen(ch) which messes up my logic, and I can't find a solution for this.

 int strtoi(char* ch)
 {   
  int sum {0};
  int len = static_cast<int>(std::strlen(ch));
  int skipLast = static_cast<int>(static_cast<int>(ch[0]) == 45);

  //Integer Method
  for(int i = len - 1; i >= 0 + skipLast; i--)
  {
    if(static_cast<int>(ch[i]) < 48 || static_cast<int>(ch[i]) > 57)
      return 0;
    sum += (ch[i]-48) * std::pow(10,i-skipLast);
  }

   sum = skipLast == 1 ? -sum : sum;
   return sum;
 }

int main()
{
  char pos[3] {'1','2','3'};
  std::cout << strtoi(pos) << std::endl;
  char neg[4] {'-','1','2','3'};
  std::cout << strtoi(neg) << std::endl;
  return 0;
}

Returns: 0 and -123. The len variable in my function doesn't get the expected value for the first call and I assume it is because neg[4] allocates more memory then pos[3]. However, for the second case:

int main()
{
  char* pos;
  pos = new char[3] {'1','2','3'};
  std::cout << strtoi(pos) << std::endl;
  char* neg;
  neg = new char[4] {'-','1','2','3'};
  std::cout << strtoi(neg) << std::endl;
  return 0;
}

Returns 123, -123. The expected result. I guess this happens because in the first case the compiler is allocating memory for the function and its argument according to the char[4] array. Is this correct? How it work for the second case, how is the compiler allocating memory to the function for the dynamic variables? And what is a possible solution to make the function work for both cases? Thanks in advance for any help.

Aucun commentaire:

Enregistrer un commentaire