/* takes a string and reverses it without making a copy of the original array *
ID: 3827833 • Letter: #
Question
/* takes a string and reverses it without making a copy of the original array
* My algorithm:
* (1) get word
* (2) get size of word
* (3) send poiinter to function
* (4) use temps to revesrse
*/
#include
#include
#define MAXLENGTH 1000
/* takes string and string size and reverses it suiing poointers */
void reverseWord(char *word, int size)
{
int ptrArray[size];
for(int i = 0; i < size; i++)
{
ptrArray[i] = word+i; // collects addresses in an array
}
int j = size-1;
for(int i = 0; i < size; i++)
{
word[i] = &ptrArray+j; // assigns contents in reverse // i just relised this will not work because contents will change as it runs.
j--;
}
}
int main(int argc, char **argv)
{
/* get String */
char word[MAXLENGTH];
printf("Enter a string ");
scanf("%s",word);
/* get size of string */
int size = strlen(word);
printf("size = %i ",size);
/* reverse string */
reverseWord(word, size);
printf(" Your string reversed is '%s' ",word);
return 0;
}
Explanation / Answer
You are not dpoing inplace reverse. Here is the fixed code.
#include <stdio.h>
#include <string.h>
#define MAXLENGTH 1000
/* takes string and string size and reverses it suiing poointers */
void reverseWord(char *word, int size)
{
int c, i, j;
for (i = 0, j = size - 1; i < j; i++, j--)
{
c = word[i];
word[i] = word[j];
word[j] = c;
}
}
int main(int argc, char **argv)
{
/* get String */
char word[MAXLENGTH];
printf("Enter a string ");
scanf("%s",word);
/* get size of string */
int size = strlen(word);
printf("size = %i ",size);
/* reverse string */
reverseWord(word, size);
printf(" Your string reversed is '%s' ",word);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.