0

I am very new to C++ , and I am wandering why this code:

void display(int display[]){
    for(int i=0;i<sizeof(display)/sizeof(int);i++){
        cout<<display[i];
    }
  }

int main()
{

    int arr[]={3,1,2,5,10,20};
    display(arr);
}

prints only the first 2 elements from the array ? why not all of them? Am I missing something?

Florin123
  • 33
  • 5
  • 1
    Does this answer your question? [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – TruthSeeker May 06 '22 at 09:09
  • 1
    When declared as a function argument, `int display[]` is actually the same as `int* display`. That is, all you have is a pointer to the very first element of the array. When you get the size of a pointer, you get the size of the pointer itself only. – Some programmer dude May 06 '22 at 09:09
  • `sizeof(display)/sizeof(int)` is not the size of the array. There is a duplicate but I dont find it – 463035818_is_not_an_ai May 06 '22 at 09:11
  • Try using ```std::span``` instead (and don't forget to ```#include ```). ```std::span``` is a sequence container, like an array, that knows its size. You'll have to use ```std::span::size``` to get its size in elements. Take a look here: https://en.cppreference.com/w/cpp/container/span (Note that span is only available with C++20 or higher) – Jonathan S. May 06 '22 at 09:12
  • https://stackoverflow.com/a/1461466/4139593 – TruthSeeker May 06 '22 at 09:12
  • Ohh, I got it , I thought it's like in java, thank you a lot guys – Florin123 May 06 '22 at 09:16
  • Almost nothing in C++ is like in Java. Better don't try to try to draw conclusions from similar looking syntax, the two languages are very different – 463035818_is_not_an_ai May 06 '22 at 09:27
  • @463035818_is_not_a_number yes I can see that, it's harder for sure, but I just need to know the basics, don't think it will take that long, I mean the pointers will be a problem xDDD – Florin123 May 06 '22 at 09:47
  • pointers is not "basics". You need pointers to understand whats going on in all details, but for writing C++ code raw pointers are very overrated in teaching and tutorials – 463035818_is_not_an_ai May 06 '22 at 09:55

0 Answers0