0

Output of C++ code

Hello again, Can someone explain this code. I understand n1, but not n2. How can sizeof(p) be 8 bytes, when it is an array of 9 ints? #include <iostream> using namespace std; int main() { int mas[9]={2,6,3,9,1,0,5,8,4}; int *p = new int[9]; for (int i=0; i<9; ++i) { p[i] = mas[i]; } int n1 = sizeof(mas)/sizeof(*mas); int n2 = sizeof(p)/sizeof(*p); cout << n1 << n2; return 0; }

25th Jan 2021, 8:49 PM
Edward Finkelstein
Edward Finkelstein - avatar
13 Respuestas
+ 9
It is not an array! It's a pointer, and pointers store memory addresses, they have size 32 or 64 bits (8bytes) And please delete the memory you borrow when you don't need it anymore
25th Jan 2021, 9:02 PM
Angelo
Angelo - avatar
+ 3
Martin Taylor, Thanks, learned something new today
25th Jan 2021, 11:30 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 2
Martin Taylor It appears you are right: https://code.sololearn.com/crxx92841Pm3/# How did you know it? Why is memcpy more efficient?
25th Jan 2021, 10:39 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 2
Martin Taylor, Then it makes sense why memcpy takes a shorter time since there is only one transfer as opposed to 9, in this case? But I don't know what you mean by optimized, since this appears to be a standard function from string.h, I would assume it is optimized, or else no one would use it? Yes, the clock_t type and clock() function are pretty nifty, I came across them when trying to compare recursive vs iterative solution for Fibonacci, if you input 30 below, you see there is a major difference. https://code.sololearn.com/cr0bbz1x5t65/# https://code.sololearn.com/cr0bbz1x5t65/# Btw, you seem very knowledgeable, what is your background? I am an undergrad physics student, graduating this May. update: it seems I flopped the cout statements, now it seems for-loop is faster?
26th Jan 2021, 2:44 AM
Edward Finkelstein
Edward Finkelstein - avatar
+ 2
Martin Taylor "When I ran your code on my local machine I couldn't get a reading higher than 0.00005 msecs for anything! The SoloLearn server is multitasking multiple users at the same time so will process the code slower than a local machine." So I increased the array size to 2000 (https://code.sololearn.com/cRi071czkxxM/#) and now the difference is more apparent: https://code.sololearn.com/cCQdSZCyH562/#
26th Jan 2021, 4:47 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 2
Nice very nice discussed and agreed that we can all learn from each other. This is very educational for a lot of SoloLearn enthousiasts. Thanks for your efforts to teach 👍🤗
27th Jan 2021, 10:04 AM
🇺🇸 Anatoli🇧🇪🇪🇺 ,
🇺🇸 Anatoli🇧🇪🇪🇺 , - avatar
+ 1
sizeof(p) will give you size of that pointer only not for whole integers stored inside.
25th Jan 2021, 9:06 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
Angelo, thanks. This is from a code challenge, but I agree there needs to be a delete [] p; at the end.
25th Jan 2021, 9:22 PM
Edward Finkelstein
Edward Finkelstein - avatar