954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

string manipulation

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.

Shaabangbang
Light Poster
41 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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.

Clinton Portis
Practically a Posting Shark
833 posts since Oct 2005
Reputation Points: 237
Solved Threads: 118
 
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

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

>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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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.

Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
 

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? [code]

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.

Shaabangbang
Light Poster
41 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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;
    }
}
Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
 

> 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 ;)

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 
(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.

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

>

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?

Shaabangbang
Light Poster
41 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 
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.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

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?

Shaabangbang
Light Poster
41 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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

Shaabangbang
Light Poster
41 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 
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.

Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
 

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

output[counter] = '\0';


Good luck, LamaBot

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

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
Shaabangbang
Light Poster
41 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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.

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

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.

Shaabangbang
Light Poster
41 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

>>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];

Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You