-3

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!!

Suraj Palwe
  • 2,080
  • 3
  • 26
  • 42
  • `sizeof(data)` doesn't do what you think it does. You need to pass the actual array size to the function as parameter, there's no other way to do it. – πάντα ῥεῖ Jul 27 '15 at 18:24
  • Also see http://stackoverflow.com/questions/1328223/sizeof-array-passed-as-parameter – πάντα ῥεῖ Jul 27 '15 at 18:27
  • 1
    If you just started learning C++, I'd advise you to read up on vectors and use them instead of arrays. – dhavenith Jul 27 '15 at 18:29
  • @dhavenith okay, thanks for suggestion – Suraj Palwe Jul 27 '15 at 19:49
  • 1
    @SurajPalwe in Function `void printArray(int data[])` data is treated as a pointer, and when you do `sizeof()`, it is giving you the size of a pointer. In `main()`, when you are using `sizeof()`it is giving you the number of bytes allocated to `data`. And your loop is running for that many times, hence the garbage value. To get the number of elements, you can use int num_ele = sizeof(data)/sizeof(data[0]); To get the number of elements in function, you must pass the size along with the array. – Nishant Jul 28 '15 at 07:20
  • @Nishant .. cool. thanks I understand now what my code was doing. your explanation was very simple and to the point!! – Suraj Palwe Jul 28 '15 at 07:31

1 Answers1

2

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   
}
yizzlez
  • 8,757
  • 4
  • 29
  • 44