c++ - Reverse an array in pointer -


here question:

write function void reverse(char s[]) reverses character string. example, “harry” becomes “yrrah”.

and here code :

void reverse(char s[]); int main() {     char s [] = "harry";     reverse(s);     cout << s << endl;      system("pause");     return 0; }  void reverse(char s[]) {     int length = strlen(s);     int c, ,j;      for(int i=0, j=length-1 ; i<j ; i++, j--)     {         c = s[i];         s[i] = s[j];         s[j] = c;     } } 

it works reverse string. however, asked in pointer. thought, first assign p pointer first char in string. assign q pointer last char of string. loop thru reverse array. when tried last char:

char *q = strlen(s-1); 

i got error. can me fix using pointer?

updated portion

if (strlen(s) > 0( { char* first = &s[0]; char*last = &s[strlen(s)-1]; while(first < last) { char temp = *first; *first = *last; *last = temp; ++first; --last; } } 

try that.

char* left = &s[0]; char* right = &s[length-1]; for(; left<right ; left++, right--) {     c = *left;     *left = *right;     *right = c; } 

and read http://www.cplusplus.com/doc/tutorial/pointers/


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -