Hello, i have a question about string manipulation, i am supposed to write a function that takes a character array and returns a void, so far so good, but its supposed to reverse the array as output, for example, if the input is "Hello" the output is "olleH", here is where the problem comes, the function is not supposed to print the string in reverse, it actually reverses it in memory. this is where im stuck, i dont know how to reverse the string in memory, like i was thinking i could use strlen to find the length of the array, then use strcpy to copy it into a new blank array, and reverse that new array. but i dont know how to reverse the string in memory.

P.S. i dont want you to solve it for me, i just need help on how to do it, any help is greatly appriciated.

Recommended Answers

All 23 Replies

one simple strategy, would be to pass the char array into your function as a reference.. therefore any manipulations you perform on the char array will affect it directly in memory.

algorithmically, reversing the array is simple. create a new dynamic temporary char array of equal length. copy first element to last element, copy first element+1 to last element-1, copy first element+2 to last element-2 etc. Then, copy the temp array back to the original array.

that's all there is to it.

Hello, i have a question about string manipulation, i am supposed to write a function that takes a character array and returns a void, so far so good, but its supposed to reverse the array as output, for example, if the input is "Hello" the output is "olleH", here is where the problem comes, the function is not supposed to print the string in reverse, it actually reverses it in memory. this is where im stuck, i dont know how to reverse the string in memory, like i was thinking i could use strlen to find the length of the array, then use strcpy to copy it into a new blank array, and reverse that new array. but i dont know how to reverse the string in memory.

P.S. i dont want you to solve it for me, i just need help on how to do it, any help is greatly appriciated.

One obvious way is to use a for loop or while loop; example:

void reverseString(const char *input, char *output, int buffer_len) {
   int counter = 0;
 
   for (;buffer_len >= 0; buffer_len--) 
  {
    ouput[counter] = input[buffer_len];
    counter++;
  }
  buffer_len[counter] = '\0';
}

That is just one way but might help give you some ideas. If you decide to use the above function, it is important that buffer_len is equal or less than the size of input or it'll overwrite the stack or produce a buffer overflow.

Good luck, LamaBot

>i dont know how to reverse the string in memory
How would you reverse "a"? Do nothing, clearly because the reverse of "a" is "a". What about "ab"? Mightn't you just swap the characters like this?

char save = str[0];
str[0] = str[1];
str[1] = temp;

Keep adding more characters and see how you would swap them around to reverse the string until you find a pattern. That's your algorithm for an in-place string reversal.

I used your question to see if I could do it. I know is not exactly what you are asking. If I understand correctly, you want a void function, and main is not void. However, I though to post my code as another, problably not so elegant, idea.

Some of the loops are just for testing and prove that the memory addresses are the same. The "NULL" can be avoided to swap at first address if you want.

#include <stdio.h>

int main()
{
    char hi[] ="Hello";
    char ih[sizeof(hi)];
    char *hi_ptr;
    size_t i;
    int length;

    hi_ptr = hi;

  /* to prove the memory addresses */
    for(i = 0; i < sizeof(hi) / sizeof(char); i++)
    {
        printf("Memory location of hi[%d] = %d, and in it lives %c\n", i, hi_ptr++, hi[i]);
    }
    
    strcpy(ih, hi);

    length = strlen(ih);
    
  /* set the pointer again since it was moved displaying the preview addresses */
    hi_ptr = hi;
     
    for(i = 0; i < sizeof(ih) / sizeof(char); i++)
    {
        *(hi_ptr + i) = ih[length - i]; /* swap happens here */
    }
    
    putchar('\n');
    
 /* to prove memory addresses are the same */
    for(i = 0; i < sizeof(hi) / sizeof(char); i++)
    {
        printf("Memory location of hi[%d] = %d, and in it lives %c\n", i, hi_ptr++, hi[i]);
    }

    getchar();
    return(0);
}

I'm going to try now using Narue suggestion.

hmm, i like clinton portis's idea, to create a new dynamic temporary char array of equal length. copy first element to last element, copy first element+1 to last element-1, copy first element+2 to last element-2 etc. Then, copy the temp array back to the original array.

but how would i code that? would it be something like this?

void reverse (const char *array)
{
    int i, 
    length = strlen (array);
    for (i = 0; i <= length; i++){
        strcpy (array, temparray);

ok, now here i dont know how to copy first element+1 to last element - 1, then first element+2 to last element - 2.

also, excuse the abysmal coding, im a first year student and this is my first time doing a high level language like C.

This is another way I have been playing with.

/*
 * gnirts.c
 *
 * plays with the idea of reversing a given
 * array of characters, in memory.
 */
#include <stdio.h>

void reverse_s(char *string);

int main(void)
{
    char hi[]="Daniweb is the best";
    size_t index;

  /* show me the content and memory location */
    for(index = 0; index < sizeof(hi) / sizeof(char); index++)
    {
        printf("Hi[%d] = %c living at %d memory address\n", index, hi[index], &hi[index]);
    }

  /* reverse the array in memory */
    reverse_s(hi);
    
    putchar('\n');
    
  /* show me the content and memory location after upsetting the array :) */
    for(index = 0; index < sizeof(hi) / sizeof(char); index++)
    {
        printf("Hi[%d] = %c living at %d memory address\n", index, hi[index], &hi[index]);
    }

    getchar();
    return(0);

}

/*
 * reverse_s function
 * parameter: a pointer to a string
 *
 * reverse a given string
 */
void reverse_s(char *string)
{
   char save;
    size_t i;
    
   int len = strlen(string);
   
    for(i = 0; i < (len / 2) + 1; i++)
    {
        save = string[i];
        string[i] = string[len - i];
        string[len -i] = save;
    }
}

> ok, now here i dont know how to copy first element+1 to last element - 1
First of all, allocate an array of equal length.

char *reversedString;
reversedString = (char*)malloc(sizeof(char)*strlen(string)+1);

Now all you need to do is loop through each char. Use the array operators [] to reference each individual charactar.

reversedString[i] = string[stringLength-i];

(Assuming that you've already set stringLength to equal the length of string .)

[edit] And don't forget the terminating null character \0 ;)

(Assuming that you've already set stringLength to equal the length of string .)

One additional note: I forgot to mention that the actual amount that stringLength will have to contain is the strlen of string-1, to compensate for arrays starting at element 0.

>

char *reversedString;
reversedString = (char*)malloc(sizeof(char)*strlen(string)+1);

Now all you need to do is loop through each char. Use the array operators [] to reference each individual charactar.

reversedString[i] = string[stringLength-i];

[edit] And don't forget the terminating null character \0 ;)

hmm, why did you put (char*) in brackets? also whats malloc? like what does the variable stand for? or are you calling by value?

hmm, why did you put (char*) in brackets?

Its called casting . In this specific case its the casting of void pointer retuned by malloc to a pointer to a char.

also whats malloc? like what does the variable stand for? or are you calling by value?

A litte google would have answered your question nicely. Like this.

hmm, well we havent covered casting yet, or the built-in function malloc, so can i just put

for (i = 0; i < len; i++)
strb[len-1-i] = stra[i];

to copy the first element +1 to last element - 1, then first element + 2 to last element - 2, and so on?

OHHH, alright, ok i get what joeprogrammer was doing now, thanks alot guys, i'll give it a shot and keep u guys posted!!!

This is just to follow up on my previous example:

#include <stdlib.h>
#include <stdio.h>
 
#define STR_SIZE 10
 
void reverseString(const char *input, char *output, int buffer_len);
static inline void cpystr(const char *input, char *output)
{
    int i;
    for (i=0;i<strlen(output);i++)
        output[i] = input[i];
}
int main (void)
{
   char original_str[STR_SIZE] = "Reverse Me";
   char reversed_str[STR_SIZE];
 
   reverseString(original_str, reversed_str, strlen(original_str)-1);
   printf("Original string non-copied: %s\n", original_str);
   cpystr(reversed_str, original_str);
   printf("Original string copied: %s\n", original_str);
}
/* This function will reverse the input and put the resulting string in output */
void reverseString(const char *input, char *output, int buffer_len)
{
   int counter = 0;
   for (;buffer_len >= 0; buffer_len--) 
   {
      output[counter] = input[buffer_len];
      counter++;
   }
   output[counter] = '\0';
}

Good luck, LamaBot

This is just to follow up on my previous example

Thank you for posting this code. I will study it.

However when I run it, this is the output I get:

Original string non-copied: Reverse MeÇ|¿ "
Original string copied: " ¿|ÇeM esreveR

I'm sure it can be fix very easy to not show the extra characters.

Make sure you've got the following statement within and at the end of the "reverseString" function:

output[counter] = '\0';

Good luck, LamaBot

ok, i've gathered some ideas from here and there and have made the following code, i keep getting crazy errors though, and i dont know how to fix them, as much as i try, i will still get the exact same error.

#include <stdio.h>
void reverse (char string[]);
int main (void)
{
char string[100];
char rstring[100];
int i;
printf ("Enter Text: ");
gets (string);
reverse (string);
printf ("%d reversed is %d\n", string, rstring);
}
 
/*takes string character array*/
/*finds stringlength, then copies array into a temporary array, then reverses it*/
 
void reverse (char string[])
{
char rstring [100];
int i;
int stringlength;
 
stringlength = strlen (string);
 
strcpy (rstring, string);
 
rstring = (char*)malloc (sizeof (char) *strlen(string) + 1);
 
for (i = 0; i < stringlength; i++){
rstring [i] = string [stringlength - i];
}
}

the errors i get are:

"String.c", line 27: warning: implicit function declaration: strlen
"String.c", line 29: warning: implicit function declaration: strcpy
"String.c", line 31: warning: implicit function declaration: malloc
"String.c", line 31: left operand must be modifiable lvalue: op "="
cc: acomp failed for S.c

You forgot to include some headers. To use strlen() and strcpy(), include string.h . For memory allocation, include stdlib.h .

Additionally, you don't need to declare rstring as a char array, as you allocate the memory with malloc. Simply declare it as a pointer; it will work.

char *rstring;

I also mentioned that stringlength should be equal to strlen(string)-1, to compensate for arrays starting at 0. If you don't do that, you'll be accessing memory you shouldn't be accessing in the last iteration of the loop.

Oh, yeah, thanks, ok it compiles correctly now, but i keep on getting a segmentation fault, i tried debugging but i still cant find where it messes up!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
void reverse (char string[]);
int main (void) 
{
char string[100];
char rstring;
int i;
printf ("Enter Text: ");
scanf ("%s", string);
reverse (string);
 
printf ("reversed is %s\n", string);
}
 
void reverse (char string[])
{
 
char *rstring;
int i;
int stringlength;
stringlength = strlen (string)-1;
strcpy (rstring, string);
rstring = (char*)malloc (sizeof (char) *strlen(string) + 1);
 
for (i = 0; i < stringlength; i++){
rstring [i] = string [stringlength - i];
}
strcpy (string, rstring);
}

P.S. i put another strcpy at the end so i can copy the temp array back to my original array, then print.. but even without the strcpy i still get a segmentation fault.

>>char *rstring;

This is not a string. It is a pointer to type char. In order to use rstring as a string you need to give it some memory. The segmenation fault comes when trying to use rstring as a string.

do something like this:
char rstring[256];

or this:

char * rstring = new char[256];

Your problem area is:

strcpy (rstring, string);
rstring = (char*)malloc (sizeof (char) *strlen(string) + 1);

You need to first allocate the memory and then perform string copy and not the other way around.

Also, you don't need a temporary for this purpose. You can always do in place swapping.

char* reverse_string ( char* my_str )
{
    char tmp = '\0' ;
    int i, j ;
    int str_length = strlen (my_str) ;

    for ( i = 0, j = str_length - 1; i < j ; ++i, --j )
    {
         tmp = my_str [i] ;
         my_str [i] = my_str [j] ;
         my_str [j] = tmp ;
    }

    return my_str ;
}

Yeah but my specific instructions were to do reversal in memory,thanks though

AHH alright, i got it:), thank you so much everyone!! i solved it! both recursively and iteratively!!

i need a program that that search strings like x,y values from a file path and after finding that x,y values, it give the output in other format ie.suppose after seraching from text file i have x value 33.5 and y value 77.5 then program should change the value of x as .3350000000D+2 and y as .775000000000D+2.

Please help me .....Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.