Skip to content

Instantly share code, notes, and snippets.

@dakk
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakk/99cf800e72b17183a9e2 to your computer and use it in GitHub Desktop.
Save dakk/99cf800e72b17183a9e2 to your computer and use it in GitHub Desktop.
Remove an element from an array and re-compact it, with recursion
#include <stdio.h>
#include <malloc.h>
#define N 8
/** Recursive delete like a pro
* where: 'ar' is the array, 'n' is the size, 'start' is 0 when
* called first time, 'irem' is the index of element to remove.
* @return the new size of the array (n-1)
*/
int recdel (int *ar, int n, int start, int irem)
{
if (start == n-1)
return start;
if (start >= (irem-1))
ar[start] = ar[start+1];
return recdel (ar,n,start+1,irem);
}
void print_ar (int *a, int n)
{
for (int i=0;i<n;i++) printf ("%d ", a[i]);
printf ("\n\n");
}
int main ()
{
int *ar = (int *) malloc (sizeof(int) * N);
// Inizializzo con numeri a caso
for (int i=0; i<N; i++) ar[i] = i+1;
print_ar (ar, N);
printf ("Elimino il 6' elemento\n");
// Elimino il 6 elemento e ricompatto
int n = recdel (ar, N, 0, 6);
print_ar (ar, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment