Swap the ath and bth of the string array passed by arr.
--It does not take into account that realloc will fail. --All the caveats with realloc apply.
str_swap.c
#include <stdlib.h>
#include <string.h>
void str_swap(char** arr, int a,int b ){
char* tmp = realloc(tmp,sizeof(char)*(strlen(arr[b])+1));
strcpy(tmp,arr[b]);
arr[b] = realloc(arr[b],sizeof(char)*(strlen(arr[a])+1));
strcpy(arr[b],arr[a]);
arr[a]= realloc(arr[a],sizeof(char)*(strlen(tmp)+1));
strcpy(arr[a],tmp);
free(tmp);
}
It was necessary to swap any element of a string array that had elements with different string lengths. Since each element has only the memory of its own length, it cannot be assigned a character string longer than that. I have reallocated it.
First post!
Recommended Posts