Problem with arrays in visual studio (program problems)

0

When I want to set the limit of my vector with a variable, the program does not let me. This did not happen to me with code blocks.

The code:

#include <iostream>

using namespace std;

int main()
{
    int save,num,c=0,digito,mayor=0;
    cout << "ingrese un numero:";
    cin>>num;
    save=num;
    while (num>0){
        num/=10;
        c++;
    }
    cout<<"tu numero tiene: "<<c<<" digito"<<endl;
    int vect [c*2];
    for(int i=0;i<(c*2);i+=2){
    vect[i]=0;
    }
    for(int i=1;i<(c*2);i+=2){
        digito=save%10;
        vect[i]=digito;
        save/=10;
    }
    for(int i=0;i<c*2;i++){
        cout<<vect[i];
    }
    cout<<endl;
       for(int i=0;i<c*2;i++){
        if(vect[c]>mayor){
            mayor=vect[i];
        }
    }
    cout<<"el mayor es "<<mayor<<endl;
    return 0;
}
    
asked by fernando quinteros gutierrez 17.03.2018 в 03:45
source

1 answer

1
int vect [c*2];

Here you are trying to create a fixed-size array using a variable ... something that is known by the acronym VLA (Variable Length Array) and that is not supported by the standard ... then it may work for you with some compilers but it's not the way to solve the problem.

You want to give the vector a size at runtime and for that you have to resort to dynamic memory:

int* vec = new int[c*2];

Of course, every new has to have its corresponding delete so that the program does not have memory leaks:

int main()
{
  // ...

  delete[] vec;
  return 0;
}

Although of course, being strict, the problem can be solved quietly without using a single vector:

  • Calculating the number of digits of a positive integer is as simple as calculating your log10 and adding 1:

    log10(1)   = 0
    log10(10)  = 1
    log10(100) = 2
    // ...
    
  • To calculate the highest digit you only need to iterate over its digits and keep the highest one ... but without vectors

That is:

int num;
std::cout << "ingrese un numero:";
std::cin>>num;

int numDigitos = static_cast<int>(std::log10(num))+1;
std::cout << "Tu numero tiene: " << numDigitos << " digito(s)\n";

int mayor = 0;
while( num != 0 )
{
  int digito = num % 10;
  num /= 10;

  if( digito > mayor )
    mayor = digito;
}

std::cout << "El mayor es " << mayor << '\n';
    
answered by 19.03.2018 в 08:01