Reverse a string of any length using pointers in C -
this question has answer here:
- how reverse string in place in c or c++? 26 answers
- how read unlimited characters in c 3 answers
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
Post a Comment