0

I was just browsing through some interview questions and found this code to reverse a string using pointers. But I see that here they have defined char string[100] which limits the string length. I am not so good at C. How do I modify the same to make it a string of any length?

#include<stdio.h>

int string_length(char*);
void reverse(char*);

main() 
{
   char string[100];

   printf("Enter a string\n");
   gets(string);

   reverse(string);

   printf("Reverse of entered string is \"%s\".\n", string);

   return 0;
}

void reverse(char *string) 
{
   int length, c;
   char *begin, *end, temp;

   length = string_length(string);

   begin = string;
   end = string;

   for ( c = 0 ; c < ( length - 1 ) ; c++ )
      end++;

   for ( c = 0 ; c < length/2 ; c++ ) 
   {        
      temp = *end;
      *end = *begin;
      *begin = temp;

      begin++;
      end--;
   }
}

int string_length(char *pointer)
{
   int c = 0;

   while( *(pointer+c) != '\0' )
      c++;

   return c;
}
Rancho
  • 309
  • 4
  • 12

3 Answers3

1

Instead of static array use dynamic memory allocation: char *tab = malloc(n * sizeof(char)) where n is some variable representing desired length.

Adrian
  • 1,166
  • 6
  • 15
  • It is not that easy. This will still limit the amount of characters that can be read. The memory is just put somewhere else (on the heap instead of the stack). – Bart Friederichs Apr 19 '13 at 06:31
  • But it definitelly pushes the limit. Ultimate solution would be to read input from file and write output to file, but I doubt it is desired solution. – Adrian Apr 19 '13 at 06:33
  • 1
    @BartFriederichs Can you kindly explain how it will still limit the amount of characters that can be read?Can't n be arbitrary? – Rüppell's Vulture Apr 19 '13 at 06:33
  • @BartFriederichs You mean limited by the total memory available right? – Rüppell's Vulture Apr 19 '13 at 06:34
  • @SheerFish yes `n` can be arbitrary, but it is still a limit. The question wants **any** size. I'll read that as limited by hardware, not software. – Bart Friederichs Apr 19 '13 at 06:37
1

You can use malloc() for this purpose if you want the size to be decided/inputted by the user at runtime.

malloc()

Rüppell's Vulture
  • 3,583
  • 7
  • 35
  • 49
0

Dynamic memory allocation is the solution.. Take a pointer to the string and allocate the memory dynamically.. this allocates at run time.. This will solve your problem..

char *str;
str = (char*)malloc(n *sizeof(char));

NOTE: typecasting is optional in C and 'n' here is the required length.(can be user input).

Raghu Srikanth Reddy
  • 2,703
  • 33
  • 29
  • 42