The proper way to implement variable length arrays in C is with malloc.
#include <stdlib.h>
void makeArrayOfSize(int size) {
// Create memory for array
char *chars = (char *)malloc(size * sizeof(char));
// Do business logic
free(chars); // ALWAYS free pointers to allocated memory to avoid leaks
}
Though, you can make a string reverser without copying the string (IF it is not hard-coded to the string table)...
void reverse(char* string) {
int length = 0;
int index = 0;
char temp;
// Ensure string is not null
if (!string) {
return;
}
// Get length assuming string has proper '\0' char at the end
while (string[length]) {
++length;
}
// Play catch!
while (index < length / 2) {
temp = string[index++];
string[index - 1] = string[length - index];
string[length - index] = temp;
}
}
Disclaimer: I didn't compile or run this code... but it reminded me of an old homework assignment so I found it nostalgic to give it a shot :)
Edit: Compiled this code. Works perfectly unless the string is hard-coded in the string table (will produce a bus error). Also will not crash if string is empty.
Took longer to write a good test than the code but here's the test and the output showing working dynamic data, but an error on the hard string:
int main(int argc, char** arcv) {
char *string;
char string0[0];
char string1[1];
char string2[2];
char string3[3];
char string4[4];
char string5[5];
char string6[6];
char *string7 = "abcdef";
string2[0] = 'a';
string3[0] = 'a';
string3[1] = 'b';
string4[0] = 'a';
string4[1] = 'b';
string4[2] = 'c';
string5[0] = 'a';
string5[1] = 'b';
string5[2] = 'c';
string5[3] = 'd';
string6[0] = 'a';
string6[1] = 'b';
string6[2] = 'c';
string6[3] = 'd';
string6[4] = 'e';
printf("String: %s\n", string);
reverse(string);
printf("Reverse String: %s\n", string);
printf("String0: %s\n", string0);
reverse(string0);
printf("Reverse String0: %s\n", string0);
printf("String1: %s\n", string1);
reverse(string1);
printf("Reverse String1: %s\n", string1);
printf("String2: %s\n", string2);
reverse(string2);
printf("Reverse String2: %s\n", string2);
printf("String3: %s\n", string3);
reverse(string3);
printf("Reverse String3: %s\n", string3);
printf("String4: %s\n", string4);
reverse(string4);
printf("Reverse String4: %s\n", string4);
printf("String5: %s\n", string5);
reverse(string5);
printf("Reverse String5: %s\n", string5);
printf("String6: %s\n", string6);
reverse(string6);
printf("Reverse String6: %s\n", string6);
printf("String7: %s\n", string7);
printf("(error after this)\n");
reverse(string7);
printf("Reverse String7: %s\n", string7);
return 0;
}
Output:
String: (null)
Reverse String: (null)
String0:
Reverse String0:
String1:
Reverse String1:
String2: a
Reverse String2: a
String3: ab
Reverse String3: ba
String4: abc
Reverse String4: cba
String5: abcd
Reverse String5: dcba
String6: abcde
Reverse String6: edcba
String7: abcdef
(error after this)
Bus error: 10
gcc, you can use-std=c99to enable variable length arrays.