+ 2

Need some help understanding some concepts

So I've created a variation of a C++ function that reverses a char array using pointers. i know what to do and how to do it, but i don't understand how it works. more specifically, i know that i have to loop until the pointer pointing at the start of the array is more than the one at the end, but why does this work? Also, why do i have to pass in the size of the char array, so that the compiler doesn't give me garbage? Thanks in advance. Edit: i figured out how it works, thanks to Babak Here's the code with some added documentation: https://code.sololearn.com/cMXK1gM8kUKe

14th Jul 2018, 4:49 PM
X-1
X-1 - avatar
5 Respostas
+ 4
X-1 Q: " why do i have to pass in the size of the char array, so that the compiler doesn't give me garbage? " A: you pass the array's name as a reference to the function's parameter list along with its size because you won't pass the whole array at once to the function in order to get its size there, instead the address of the first element of the array will be passed. And also keep that in mind that array's name is not pointer, it just acts as a pointer to the first element like &A[0]. void f( int *arr /* or int are[] */, int size) { // The address field for integer pointers in 32bit architecture is 4 bytes and in 64bit one is 8 bytes. cout << sizeof(arr); } int main() { int A[] = {1, 2, 3, 4, 5}; int arr_size = sizeof(A) / sizeof(A[0]); // 20 bytes / 4 bytes = 5 (See the note at the end) f(A, arr_size); }
14th Jul 2018, 8:17 PM
Babak
Babak - avatar
+ 5
Cont.1 Q: " ... i know that i have to loop until the pointer pointing at the start of the array is more than the one at the end, but why does this work? ... " A: It's simple. Just swapping the first element of the array with the last element and continuing the trend until the loop counter reaches to the middle element of the array without any additional container (as one of the many possibilities to do that), void f( int *arr, int n) { int end = n-1; int mid = n/2; for (int begin = 0; begin < mid; ++begin) { *(arr + begin) ^= *(arr + end); *(arr + end) ^= *(arr + begin); *(arr + begin) ^= *(arr + end); --end; } } int main() { // same as above for (const int &i : A) cout << i << " "; } Output: 5 4 3 2 1
14th Jul 2018, 8:25 PM
Babak
Babak - avatar
+ 4
Cont.2 Swapping process A = 1 2 3 4 5 mid = 5 / 2 = 2 1st cycle ( A[0] <-> A[4] ) 5 2 3 4 1 2nd cycle ( A[1] <-> A[3] ) 5 4 3 2 1 Note: In case of char array, as you may already know, it is a null terminated sequence of characters, so you must consider it (subtract the whole size by 1 to eliminate the effect of '\0' in the output reversed sequence) during the size calculation process.
14th Jul 2018, 8:43 PM
Babak
Babak - avatar
+ 3
X-1 You should link the code to the thread, after saving it inside the playground.
14th Jul 2018, 5:25 PM
Manual
Manual - avatar