← Back to Pointers
Question 476
Generic Byte Swap with void Pointers and memcpy
Generic Byte Swap with void Pointers and memcpy
Write one swap function that works for any type, then use it on three of them. voidgswap(void *a, void *b, size_t size)must exchange the size bytes at a with the size bytes at b, moving them with memcpy through a malloc'd scratch buffer that it frees before returning. Read from stdin, in this order: two integers x and y; two doubles d1 and d2; five integers into an array; two indices i and j (0-based, always valid). Swap x with y, d1 with d2, andarr[i]witharr[j]— every swap through gswap, with sizeof giving the size. Print exactly three lines: "ints: " then the two integers; "doubles: " then the two doubles with exactly 2 decimal places; the five array values. Values on a line are separated by single spaces. Sample input: 3 7 2.50 9.75 10 20 30 40 50 0 4 Free the memory you allocate before the program ends — this question checks for memory leaks.
Expected Output:
ints: 7 3 doubles: 9.75 2.50 50 20 30 40 10
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
Pointers
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (p, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.