Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing char array in C programming

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.

like image 753
Sahin Avatar asked Feb 08 '23 09:02

Sahin


1 Answers

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'.

like image 167
linluk Avatar answered Feb 11 '23 23:02

linluk