tags:

views:

521

answers:

10

Is there a way to print a string of fixed size in reverse without using pointers?

#include<stdio.h>

main()
{
char buffer[10];

scanf("%s", buffer);

// need to print buffer in reverse without using pointers?? 

}
+7  A: 
#include<stdio.h>

main()
{
  char buffer[10];

  int n = scanf("%s", buffer);

  // print the number of chars written to buffer
  if (n != EOF) {
    int len = strlen(buffer);
    if (len <= 10) {
      int i;
      for (i = len - 1; i >= 0; i--)
        printf("%c", buffer[i]);  
    } 
  }
}
Key
-1 for giving an answer without any comment and that doesn't take into account the fact that the string that is read might be shorter than 9 characters. If you answer homework-type questions answer them correctly and such that the OP at least has a chance to learn something.
Jens Gustedt
`scanf()` returns the number of input items assigned (here EOF, 0 or 1), not the length of the string.
schot
@schot: true, changed some, thanks
Key
@Key, but but but OMG the `[]` is a syntax sugar for the pointer arithmetic!!! Proper answer probably should be "you can't do it in C without pointer". BTW you miss the 0th (the very first) character in the `buffer`. It should be `i >= 0`, not `i > 0`, in the loop.
Dummy00001
@Dummy: Thank for the loop error. About the pointers I interpreted it as not wanting to use the asterisk sign '*', but instead solve it by indexing the array. Although it very seldom happens, I could be wrong.
Key
@Jens: Or answer them incorrectly so that the OP learns to either (A) own up to it being homework or (B) pull out their textbook and read it.
Greg D
+2  A: 

Here's a recursive way of doing it; technically, this is using a pointer, but I wouldn't go into language-lawyer mode with such simple tasks.

#include <stdio.h>
/* If you want it printed forward, or backward, or think of another way.. */
typedef enum {
    FRONT = 1,
    BACK,
} direction;

/* Technically still using a pointer...don't nitpick. */
void echo_string(char buffer[], size_t buflen, direction from)
{
    /* An index into the buffer to echo, which will preserve
     * its value across subsequent recursive calls.
     */
    static size_t index = 0;
    /* According to the specified direction, print from the front
     * or the back of the buffer. Advance the index (a misnomer, I guess).
     */
    if(from == FRONT) {
        printf("%c", buffer[index++]);
    }
    else {
        printf("%c", buffer[buflen - ++index]);
    }
    /* Are there any more characters to echo? Yes? Awesome! */
    if(index != buflen) {
        echo_string(buffer, buflen, from);
    }
}

int main(int argc, char **argv)
{
    char buffer[10];
    scanf("%s", buffer);
    /* Better strlen() than sizeof() here,
     * but BEWARE! scanf() is DANGEROUS!
     */
    echo_string(buffer, strlen(buffer), BACK);
    return(0);
}
Michael Foukarakis
+1 for unnecessary use of recursion!
Brian Postow
A: 

You can use strrev to reverse a string.

#include <stdio.h>
#include <string.h>

main()
{
    char buffer[10];

    scanf("%s", buffer);

    strrev(buffer);
    printf("%s", buffer);
}
Scytale
+1 for actually including a comment explaining your method (although one that could be fleshed out a little!) rather than just splurging code.
Stephen
-1. `strrev` is non-standard. If you have such a function, it's pure luck, and there's an excellent chance it would be unavailable on the OP's system (whatever it is).
Nicholas Knight
@Nicholas: Thanks for adding this information. Although it might be better to try using strrev than to implement it on one’s own. For example, the current best answer (for (i = 9…) is not working with strings at all, but with char arrays. If the string terminated at buffer[3] with a null byte, that solution would start dumping arbitrary memory.
Scytale
@scytale: I concur that my answer isn't fail-safe. Returned value from scanf should be used to only print the chars set by scanf.
Key
A: 
#include <stdio.h>
#include <conio.h>

void reverse(char a[], int s, int sc );

void reverse(char a[], int s, int sc ){

if ((sc-s)<(s-1))
{
a[sc-s]^=a[s-1];
a[s-1]^=a[sc-s];
a[sc-s]^=a[s-1];
reverse (a, s-1, sc) ;

}

}

void main (){


char a[]="ABCDEFG";

reverse(a, 7, 7);
printf("%d",a);
getch(); //i just use it to freeze the screen

}
bachchan
-1 for not formatting code and using cout in C program.
SigTerm
And for using the wrong return type for main, the wrong conversion specifier for printf(), the non-standard conio.h and getch(), no newline in printf(), and the horrible XOR swap "technique".
Robert Gamble
+1 for using recursion
Yassin
+1 for using the horrible XOR swap "technique"
Greg D
+1  A: 

As caf pointed out, we're still using pointers..!

Here's an other way to solve the problem (of reversing a string). This code snippet (and probably most others) don't respect stuff like utf8. I think signines post demonstrating the K&R way was quite close to mine (:D) so I adapted mine to fit that example (and corrected some things..)

#include <stdio.h>
#include <string.h>

void strrev(char *s) {

 size_t len = strlen(s) + 1;
 size_t i, j;

 for(i = 0; i < len / 2; i++) {

  j = len-1 - i-1;

  char tmp = s[j];
  s[j] = s[i];
  s[i] = tmp;

 }

}

int main(int argc, const char *argv[]) {
 char buffer[10];

 scanf("%s", buffer); // Look out for an overflow ;)
 strrev(buffer);
 puts(buffer);

 return(0);
}
gamen
+9  A: 

A lovely K&R function to reverse your string in-place before printing it, perhaps?

#include <stdio.h>
#include <string.h>

void strrev(char *s) {
  int tmp, i, j;
  for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
    tmp = s[i];
    s[i] = s[j];
    s[j] = tmp;
  }
}

int main(int argc, const char *argv[]) {
  char buffer[10];
  scanf("%s", buffer);
  strrev(buffer);
  printf("%s\n", buffer);
  return 0;
}
signine
nice...............
Yassin
Do it with XORs and you have a classic interview question/answer.
Greg D
@Greg: Yuck, why? :)
GMan
A: 
void outstrreverse(const char s[])
{
    size_t l=strlen(s);
    while( l && s!=&s[--l] )
        putchar(s[l]);
    if(s[0])
        putchar(s[0]);
}
+5  A: 

Since [] is just syntactic sugar for pointers, here's a version that works completely without pointers, arrays or anything else, just one single int. You didn't say that the string has to be stored somehow. :) (Note that I use fgetc instead of a buffer and scanf).

[jkramer/sgi5k:.../c]# cat rev.c

#include <stdio.h>
#include <stdlib.h>

void read_print();

int main(void) {
        fputs("Enter your string, yo! ", stdout);

        read_print();

        fputs("\nDone!\n", stdout);

        return EXIT_SUCCESS;
}

void read_print() {
        int c = fgetc(stdin);

        if(c != EOF && c != '\n') {
                read_print();
                fputc(c, stdout);
        }
}
[jkramer/sgi5k:.../c]# gcc -o rev rev.c -Wall -W -Os
[jkramer/sgi5k:.../c]# ./rev 
Enter your string, yo! foobar
raboof
Done!
jkramer
+1  A: 
 reverse(char c[], int len)
 {
       if( ! (len / 2))
          return;
       char t =  c[0];   
       c[0] = c[len--];  
       c[len] = t;
       reverse(c, len-1);
 }

The error(s) is left as an exercise to the student.

Paul Nathan
A: 
TerryP