0

explain this part y=&x[0]; y=x;

main () { int x [5]; int *y=new int [20]; y=&x [0]; y=x; }

22nd Oct 2017, 3:48 PM
mir shahab
mir shahab - avatar
3 odpowiedzi
+ 1
main () { int x[5]; // (1) int *y = new int[20]; // (2) y = &x[0]; // (3) y=x; // (4) } (1) Create an array of 5 integers 'x', on the stack frame of main function. (2) Declare a pointer to integer 'y', allocate space for 20 consecutive integers in the heap, assign the starting address of the allocated space to 'y'. (3) Assign the address of the first element in array 'x' to 'y' (same as y = x). Leak the memmory allocated in (2). (4) Assign again the starting address of 'x' to 'y'. (Why?) If you want more specific explanations, ask more specific question, because it's not really obvious what part you don't understand, and what level of explanation is expected.
22nd Oct 2017, 8:15 PM
deFault
0
i did not understand last 3 lines that y is array when array name is writen it show the address of first element then who it works please explain it
23rd Oct 2017, 5:08 AM
mir shahab
mir shahab - avatar
0
The address of an array is the address of it's first element. (2) int *y = new int[20] Operator new allocates dynamic memory and returns it's address. There are forms for allocating memory for single element (like this: new int), or for an array of elements (like this: new int[size]). Here a space for an array of 20 integers is allocated, and the address of the allocated memory is assigned to the integer pointer 'y': y = new int[20]. Now 'y' is pointing to the first integer of a memory block of 20 integers in the dynamic memory. (3) y = &x[0] Here the address of the 0th element of the array 'x' is assigned to the pointer 'y'. 'x' is the array 'x'; x[0] — 0th element (it's value); &x[0] — address of 0th element. So 'y' is now pointing to the array 'x'. Also we didn't delete the previously allocated memory — hence the memory leak. (4) y=x Is effectively the same as y = &x[0], as the address of an array is the address of it's first element. So again, we are assigning the address of the array 'x' to the pointer 'y'. Links: http://www.cplusplus.com/doc/tutorial/arrays/ http://en.cppreference.com/w/cpp/language/new
23rd Oct 2017, 5:38 AM
deFault