I have a function that swaps 2d arrays in C by using memcpy. I know you can swap pointers but I'd like to do a comparison between copying the arrays and swapping pointers.
Here is my code for it, the 2d arrays are n x n.
void swap_arrays(int n, float old[][n], float new_arr[][n]) {
float temp[n][n];
int arr_size = sizeof(float) * n * n;
memcpy(temp, old, arr_size);
memcpy(old, new_arr, arr_size);
memcpy(new_arr, temp, arr_size);
}
It works fine for a 5 x 5 array, but it segfaults when the array is larger (the actual size I need is 4000+, it starts seg faulting at 2000+), at the first memcpy. Any help is appreciated.
sizeof(float) * n * nfor values ofnmuch smaller than you're wanting to use. Why do you need to swap arrays? Normally, you'd just swap their pointers. And if you do need to swap all their contents, why not use the heap instead of the stack?malloc()in many aspects. But in this case it seems impossible to avoid it.sizeof tempinstead ofsizeof(float) * n * n.