I'm newbie in C and I'm trying to do some function to reverse a word, here my code:
#include <stdlib.h>
#include <string.h>
// ƒ to revers the word
void lettreCount(char *saisi, int length){
int i, j = 0;
char revers[length];
for (i = length; i >= 0; --i){ //loop
*(revers j) = saisi[i];
j;
}
printf("%s\n",revers);
}
int main(){
char text[30]; //Array for text
int len;
printf("Saisissez le text:\n");
gets(text);
len = strlen(text);
lettreCount(text, len);
}
but I get all time just an empty string in terminal, how i should to do? thank you
CodePudding user response:
Strings in C are terminated by a null byte. So when you start your loop with i = length the first character you put in the new array is the null byte. This means you have an empty string.
Start your loop at index length-1 so you start at the last character of the string. Then after the loop, you'll need to manually add the terminating null byte to the destination array.
char revers[length 1];
for (i = length-1; i >= 0; --i){ //loop
*(revers j) = saisi[i];
j;
}
revers[length] = 0;
CodePudding user response:
Do you name all your functions as lettreCount independent on what they are doing?:)
incompatible pointer to integer conversion strchr
If a string s has length characters (the value returned by the function strlen) then the expression s[length] yields the terminating zero character '\0'. The terminating zero character is being written as the first character of the new string in this for loop in its first iteration
for (i = length; i >= 0; --i){ //loop
*(revers j) = saisi[i];
j;
}
As a result the destination array contains an empty string.
The function that creates a reversed string of a given string can be declared and defined the following way
char * copy_reverse( const char *s )
{
size_t n = strlen( s );
char *reversed = malloc( n 1 );
if ( reversed != NULL )
{
reversed[n] = '\0';
for ( char *p = reversed n; *s; s )
{
*--p = *s;
}
}
return reversed;
}
