Search code examples
c++arraysgarbage

C++ array gives me garbage value


I just started learning c++ and came to Arrays. So what I want to do is perform some function on the array that was passed in function. So for this I tried small example

#include <iostream>
using namespace std;

void printArray(int data[]){
  cout<<"len is :"<< sizeof(data)<<endl;
  for(int i = 0 ;i<sizeof(data); i++){
     cout<<data[i]<<" ";
  }
  cout<<endl;
 }

int main() {
  int data[] = {1,2,3,4,5,6};
  printArray(data);
  cout<<"in main :"<<sizeof(data)<<endl;
  for(int i = 0 ;i<sizeof(data); i++){
        cout<<data[i]<<" ";
    }
  return 0;
}

And Following is the output I obtained from the code

 len is :8
 1 2 3 4 5 6 738192384 -1126994503 
 in main :24
 1 2 3 4 5 6 738192384 -1126994503 0 0 -1061892411 32677 0 0 -1665163256 32766 0 1 4196851 0 0 0 463403231 1946389667  

I am not understanding where the process goes wrong. or is some thing in my code that make these weird changes to happen. and also the sizeof() is giving two values for the same array.Correct me where I am wrong anywhere.

I am using Eclipse software with c++ plugin added.

Thanks in advance for help!!


Solution

  • sizeof doesn't work if you pass an array to the function in this fashion. Try passing the size with the array or pass the begin and end pointers of the array.

    If you don't mind templates, you can pass the array by reference:

    template<unsigned length>
    void printArray(int (&data)[length]) {
        //length is the length of data   
    }