I am new to c programming language. I am trying to reverse elements in char array. Actually, I almost reversed but there is something that I can't make it. Here is code:
void q2_reverseTheArray(char word[100]){
int lentgh=sizeof(word);
int j;
for(j=length+1; j>=0; j--){
printf("%c", word[j]);
}
The code reverse the array but it adds another letter.
here you have a working example:
#include <stdio.h> // printf
#include <stdlib.h> // malloc, free
#include <string.h> // strlen
int main() {
char* s = "hello";
size_t l = strlen(s);
char* r = (char*)malloc((l + 1) * sizeof(char));
r[l] = '\0';
int i;
for(i = 0; i < l; i++) {
r[i] = s[l - 1 - i];
}
printf("normal: %s\n", s);
printf("reverse: %s\n", r);
free(r);
}
your code was wrong in length + 1
it should say length - 1
.
and you have to pay attention to the terminating '\0'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With