I am writing insertion sort using strings. I have char arrays like:
char array1[4] = {'a', 'b', 'c', '\0'};
char array2[4] = {'b', 'd', 'e', '\0'};
And I need to use this operation:
char string[2];
string[1] = array1;
string[2] = array2;
Is it possible ?
Because in insertion sort I need a string.
This is the insertion code:
char* insertionsort(char* a, int n) {
int k;
for (k = 1; k < n; ++k) {
int key = a[k];
int i = k - 1;
while ((i >= 0) && (key < a[i])) {
a[i + 1] = a[i];
--i;
}
a[i + 1] = key;
}
return a;
}
Short answer: no, it’s not. Arrays are not assignable. You can use
strcpyto copy the elements from one string to another, but in this case that won’t work either — you’ve definedstringas an array of 2 chars, but you’re trying to assign an entire array of chars to each of those.It’s not entirely clear that it’s what you want, but one possibility would be:
In this case,
stringis an array of two pointers to char, and the assignments set those to point to the first character of each of your previously defined strings.Since you’ve tagged this as both C and C++, I’ll add a bit about that: this is written as very much C code. If you’re actually using C++, you probably want something more like:
Even in C, I’d prefer to initialize and use string constants where they make sense:
Or even just: