Introduction
I have an algorithm which takes a pointer to a char array. The algorithm first retrieves the length of the array then reverses the array.
The problem
The problem I have is that I want to use this on a wchar_t array. And want to be able to do this without having to copy the whole function, change the name and the type of the argument.
Here is the mentioned function:
void reverseString(char *str){
unsigned int l = getStringLength(str);
int i = 0;
int m = l >> 1;
while(i < m){
str[i] ^= str[l - 1];
str[l - 1] ^= str[i];
str[i] ^= str[l - 1];
i++;
l--;
}
}
From googling and reading on SO this won’t be able to use a void pointer (conceptually same thing using a union) since it would leave me with a solution like this, which to me is equally bad as writing separate functions but with different names and argument types:
void reverseString(void *array, short typeSize){
unsigned int l = getArrayLength(array);
int m = l >> 1;
int i = 0;
char *str = 0;
wchar_t *wstr = 0;
if(typeSize == 1){
str = (char *) array;
while(i < m){
str[i] ^= str[l - 1];
str[l - 1] ^= str[i];
str[i] ^= str[l - 1];
i++;
l--;
}
}else if(typeSize == 4){
wstr = (wchar_t *) array;
while(i < m){
wstr[i] ^= wstr[l - 1];
wstr[l - 1] ^= wstr[i];
wstr[i] ^= wstr[l - 1];
i++;
l--;
}
}
}
Note: getStringLength is just a function which loops through the pointer till it gets to '\0' and returns the iteration sum.
The answer
I am looking for an answer which tells me how to do this in a nicer way without having to rewrite the internals of the algorithm, or an answer saying that it won’t be possible to do it any other way. I’m not looking for an answer telling me I should use this and that library which does this for me, because I’m not using this in production code, it’s purely educational to get a better understanding of how memory management works and other concepts alike.
Edit: The function I showed is just an example, I’m looking for a universal solution to problems with algorithms alike.
Using “generics” in C is likely to produce code that is noticeably slower and more convoluted / difficult to read / difficult to maintain than the original code. Use the preprocessor if you must do this.
My recommendation is to avoid this technique if at all possible: you should really only use
charorwchar_tin your program, not a mixture of both! (charorUCharor almost universally preferable since you can choose the encoding, but I digress…)Then, in reverse_impl.h:
Also, DO NOT DO THIS:
It is more difficult to read and quite possibly much slower to execute.
Also, note that both
reverseandwreversewill make garbage if you give them Unicode input:reversewill make malformed output andwreversecan switch the diacritics around or totally screw up Hangul, depending on how they’re represented.