I wanted to implement sorting by insertion and asked myself this question: how do I pass an array to a function so that after processing its values do not change in the main function? Suppose I want to pass an array to a function so that it is sorted there, output it in the same function, but so that its values do not change in the main function. If when I pass a regular variable to a function, it will not change, and if the array passes a pointer to the array, it will change its values to the main function.
#include <stdio.h> #include <stdlib.h> #include <ctime> #include <iostream> void PrintA(int A[], int N); void Swap(int *a, int *b); void InsertionSort(int A[], int N); int main(void) { const int N = 10; int A[N]; for (int i = 0; i < N; i++) { A[i] = 1 + rand() % 9; } printf("Array under insertion sort: \n"); PrintA(A, N); InsertionSort(A, N); /*printf("Array after insertion sort: \n"); PrintA(A, N);*/ system("pause"); } void PrintA(int A[], int N) { for (int i = 0; i < N; i++) { printf("%d ", A[i]); } printf("\n"); } void Swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void InsertionSort(int A[], int N) { int j; for (int i = 1; i < N; i++) { j = i; while (j > 0 && A[j - 1] > A[j]) { Swap(&A[j - 1], &A[j]); j--; } } PrintA(A, N); } I tried to somehow remove the pointer to the array, but then I had errors with the Swap function in the InsertionSort function.