Reverse function

Hello,

I`m learning with the Kernighan and Ritchie the C programming language and I need to write a function that reverses the character string s. Then I need to test it.
Here is what I came up with so far but didn`t work right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

/* Reverse the character string s */


#include <stdio.h>

#define MAXLINE 1000

void reverse(char s[ ]);
int getline(char line[ ], int lim);


int main()

{

   char line[MAXLINE];
   while(getline(line, sizeof line) > 0)
   {

   reverse(line);
   printf( "%s", line);
   
   }

  return 0;
 
 }



    void reverse ( char s[ ] )
 {

    char c;
    int i;

    s[i++] = c;
    ++i;

    for (i > 0; --i;)
       s[i] = c;
 }         
 


   int getline(char s[ ], int lim)
		
	{
		int c, i;
		
		for (i=0; i<lim-1 && (c = getchar()) != EOF && c!= '\n'; ++i)
		s[i] = c;
		
		s[i] = '\0';
		return i;
	}
	

 



Any suggestions where I`m going wrong would appreciate, thanks.
always use simplest approach which 1st come to mind, for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void reverse(char s[])
{
    int len = strlen(s); // get string length
    char * end = s + len - 1; // find pointer to last byte; -1 for '\0'
    int i;
    char temp;

    for (i = 0; i < len / 2; i++)
    {
        // swap bytes
        temp = *(end - i);
        *(end - i) = s[i];
        s[i] = temp;
    }

    s[len] = '\0';
}
Thank you , but we have not covered pointers or the string.h library yet. With the basic toolkit of the book provided so far, I would expect something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  
   void reverse ( char s[ ] )
 {

    char ch;
    int i, j;
    
    for ( j = 0; j < s[i]; ++j)
    {
    	;
    }
          
    for ( i = 0; i < j; ++i)
    {
       --j;
       ch = s[i];
       s[i] = s[j];
       s[j] = ch;
    }

 }


  


Not sure If I got it correctly though.
I thought if there is a cooler way to do this, at the same time making the code more readable. Let`s do some xor-swap fun too!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

/* Reverse the character string s */

/* Warning not compiled or tested anywhere */

#define XORSWAP(a, b)	((a)^=(b), (b)^=(a), (a)^=(b))
#define MAXLINE 2000

#include <stdio.h>

void reverse (char s[])
{
  
  int len = strlen(s);
  char * end = s + strlen(s) - 1;
  char ch;
  int i;
  
  
  while (s < end)
  {
    XORSWAP(*s, *end);
    i++;
    end--;
    
  }
  
}


 int main(void)
{
  char line[MAXLINE];

  while(strlen(line) > 0)
  {
    reverse(line);
    printf("%s\n", line);
  }
  return 0;
}
Topic archived. No new replies allowed.