0

here's the code:

int *num_arr = number_to_array(num);
cout<<"\nNum aaray:"<<*(num_arr+1);
display(num_arr, digit_count);

The cout statement here is showing the correct value, but display() is not. display is showing garbage values

code for display():

void display(int num_arr[],int dc)
{
cout<<"\n";
cout<<"\n"<<num_arr[0];
cout<<"\n"<<num_arr[1];
 for(int i = (dc-1); i>=0; i--)
 {
         cout<<num_arr[i];
 }

}

int* number_to_array(int num)
{
int i=0;
int num_arr[100]; // make dynamic array
  while(num!=0)
  {
    num_arr[i] = num%10;
    num  = num/10;                
    i++;
   }
return num_arr;
}

what could be the reason?

user1995120
  • 167
  • 1
  • 9
  • 2
    Could you post the display() function? – Ermir Jul 11 '13 at 09:26
  • 3
    possible duplicate of [Returning Pointer from a Function in C++](http://stackoverflow.com/questions/8969292/returning-pointer-from-a-function-in-c) – Mat Jul 11 '13 at 09:26

1 Answers1

2
  1. You are returning address of local variable (name of array is address of it's first element). It is mistake, because array will not exists after you exit a function.

  2. int num_arr[100]; // make dynamic array - it is static array, not dynamic.

Possible solutions:

  • (Prefferable) Use std::vector
  • Use dynamic arrays (int *p = new int[100])

Proposal - learn basics of C/C++: pointers, arrays, function arguments and return values.

awesoon
  • 32,469
  • 11
  • 74
  • 99
Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61