Reverse a string of any length using pointers in C -


this question has answer here:

i browsing through interview questions , found code reverse string using pointers. see here have defined char string[100] limits string length. not @ c. how modify same make string of length?

#include<stdio.h>  int string_length(char*); void reverse(char*);  main()  {    char string[100];     printf("enter string\n");    gets(string);     reverse(string);     printf("reverse of entered string \"%s\".\n", string);     return 0; }  void reverse(char *string)  {    int length, c;    char *begin, *end, temp;     length = string_length(string);     begin = string;    end = string;     ( c = 0 ; c < ( length - 1 ) ; c++ )       end++;     ( 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; } 

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


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -