ssecorp said:
char* reverse(char* str) {
int length = strlen(str);
char* acc[length];
This is problematic for at least four reasons:
a) The size of an array must be a compile-time constant unless
you have a compiler that supports C99 variable length arrays
b) You ask for 'length' pointers to char, but it looks very
much as if you just want an array of chars
c) If 'acc' would be an array of chars it would be too short by
one element if you want to store a string with the same length
as that of 'str' in it (don't forget about the trailing '\0'
char that is needed to make a string out of a mere char array)
d) You later try to pass back a pointer to the array to the caller
but this array is a local variable that vanishes the moment the
function is left and then can't be used anymore.
There are basically two ways you can get aroung the last problem.
1) Have the caller pass a second array to the function in which
you store the reversed string
2) Allocate memory for the reversed string (and tell everyone
that's going to use this function to deallocate it when it's
not needed anymore).
A third approach would be to have a static array that's long
enough for each string you will pass to this function. But there
are two difficulties. First of all knowing in advance what the
longest string that ever will be passed to the function can be
tricky ti say the least. And the reversed string can only be used
between two invokations of the function since the next invokation
will overwrite the previous result.
int i;
for (i=0; i<=length-1; i++){
acc[length-1-i] = str;
}
If 'acc' would be an array of chars (of sufficient length) it
now would contain the reversed chars from 'str'. But it's still
missing a trailing '\0' char and thus it's not a string.
And that's, as I wrote, absolutely wrong. You can't safely pass
back a pointer to a local variable for use in the caller.
How do I then print a string and not decimals? If I add printf inside
the for loop it prints decimals. they are reversed so it works but I
want to prin chars.
No idea what this means. Show your printf() call and you probably
will get an answer. But without knowing what exactly you did there
it's impossible to say.
Regards, Jens