Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

C++ Reverse Array

In C++, I need to:

  • Read in a string from user input and place it into a char array [done]
  • Then pass that array to a function [done]
  • The function is supposed to reverse the order of characters [problem!]
  • Then, back in the main(), it displays that original array with the newly reversed characters.

I'm having trouble creating the function that actually does the reversing because I have some restrictions:

  • I cannot have any local array variables.
  • No pointers either

My function is only passing in the original array ie:

void reverse(char word[])

EDIT: Here's my code base so far:

void reverse(char word[]);

void main() 
{
  char word[MAX_SIZE];

  cout << endl << "Enter a word : ";
  cin >> word; 
  cout << "You entered the word " << word << endl;

  reverse(word); 

  cout << "The word in reverse order is " << word << endl;
}

void reverse(char myword[]) 
{
  int i, temp;
  j--;

  for(i=0;i<(j/2);i++) 
  {
    temp      = myword[i];
    myword[i] = myword[j];
    myword[j] = temp; 

    j--; 
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Despite this looking quite homeworky, may I suggest:

void reverse(char word[])
{
    int len=strlen(word);
    char temp;
    for (int i=0;i<len/2;i++)
    {
            temp=word[i];
            word[i]=word[len-i-1];
            word[len-i-1]=temp;
    }
}

or, better yet, the classic XOR implementation:

void reverse(char word[])
{
    int len=strlen(word);
    for (int i=0;i<len/2;i++)
    {
        word[i]^=word[len-i-1];
        word[len-i-1]^=word[i];
        word[i]^=word[len-i-1];
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...