4

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.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Sahin
  • 63
  • 1
  • 1
  • 4
  • 2
    Are you sure this is the code you're using? This shouldn't compile, as you have a typo in the declaration of `length`; then it should crash because you start the loop by accessing `word[length + 1]` which is 2 indices out of range. – Arc676 Dec 06 '15 at 09:31
  • Your for loop conditions are wrong. Arrays are indexed from 0 to length-1. Try the following: `for (j=length-1; j>0; j--)` This will start at the last character and repeat until the first one. Better yet, become accustomed to using your debugger. – enhzflep Dec 06 '15 at 09:33
  • Yes, I am sure. I gave parameter "book". And the output was "aakoob". – Sahin Dec 06 '15 at 09:35
  • To all readers: Having said "I am new to c programming language", cut this dude some slack and refrain from down-voting or close-voting the question. – barak manos Dec 06 '15 at 09:36
  • Possible duplicate of [Sizeof array passed as parameter](http://stackoverflow.com/questions/1328223/sizeof-array-passed-as-parameter) – n. m. could be an AI Dec 06 '15 at 09:50

3 Answers3

5

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

linluk
  • 1,650
  • 16
  • 33
  • Thank you ! I solved the problem by counting each element for finding length. – Sahin Dec 06 '15 at 09:56
  • @Sahin could you please accept (_and maybe upvote ;-)_) an answer, so that the question appears answered. thanks. – linluk Dec 08 '15 at 16:10
4

The correct code is

for(j=length-1; j>=0; j--){
   printf("%c", word[j]);

This is because the string's elements are indexed from 0 to length-1. For example,

word == "Hello"
length == 5
word[0] == 'H'
word[1] == 'e'
word[2] == 'l'
word[3] == 'l'
word[4] == 'o'
Andrej Adamenko
  • 1,650
  • 15
  • 31
0

I hope this is would be the batter solution.

Without string.h header file

 main()
{
    char str1[100], str2[100];
    int i, k, j;
    scanf("%s", &str1);
    for(i=0; str1[i] != '\0'; i++ );
    j=i-1;
    for(k=0; k<=i; k++)
    {
        str2[k]=str1[j];
        j--;
    }
    for(k=0; k<i; k++)
        printf("%c", str2[k]);
    return 0;
}