Thread: String reversing and benchmark in C

  1. #1
    Registered User
    Join Date
    Dec 2018
    Posts
    13

    Question String reversing and benchmark in C

    Im trying to do the C version of something like that in c++:

    Code:
    #include <string>
    #include <bits/stdc++.h>
    #include <cstdio>
    
    
    std::string reverseString (std::string str )
    {
      std::string result = "";
      for (int i = str.length()-1 ; i > -1 ; i--)
        {
            result += str[i];
        }
      return result;
    }
    
    
    int main()
    {
        std::vector<std::string> Tvec(0xdeaad,"Test_Strings");
        std::cout << "Running for " << Tvec.size() << " test cases." << "\n";
    
    
        auto t1 = std::chrono::high_resolution_clock::now();
        for (auto &s : Tvec)
        {
            std::string tested = reverseString(s);
        }
        auto t2 = std::chrono::high_resolution_clock::now();
        auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count();
        std::cout << "Duration1 : " << duration1 << "\n";
        
        return 0;
    }

    I have wrote this so far but it seems all bad and wrong on so many different levels:
    Code:
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    char reverseString4(char *str)
    {
      size_t strsize = strlen(str);
    
      char result[strsize];
      for (size_t i = strsize; i > 0; --i) {
        result = str;
      }
      return result;
    }
    
    int main(void)
    {
      int test_runs = 4096;
      const char *test_word = "deadbeef";
      size_t test_word_len = strlen(test_word);
      char *TEST_ARR[test_runs][test_word_len];
      for (size_t i = 0; i < test_runs; i++) {  //Need to find a way to benchmark the exec time.
        TEST_ARR = test_word;
      }
    
      return 0;
    }
    Is there any way I can achieve something like from that first cpp code but in c?
    Last edited by Salem; 01-31-2022 at 09:36 PM. Reason: Removed crayola

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I suggest a function prototype like this:
    Code:
    char *reverseString4(const char *str);
    To implement roughly the same thing as the C++ code, you would:

    1. Call strlen to find out the length of str.
    2. Call malloc() to allocate storage for the result string, using the length of str + 1.
    3. Append to the result string by traversing str in reverse, remembering to null terminate. (Note that your attempt in C is incorrect.)
    4. Return the result string.

    Note that this means that the caller is responsible for calling free(). Another approach would be to implement two separate functions that are used together: one to reverse the string in-place and another to make a copy of the string, but this would be somewhat different from what you're doing in C++.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    @OP,

    did you write the C++ code or did you find it somewhere ?

  4. #4
    Registered User
    Join Date
    Dec 2018
    Posts
    13
    Quote Originally Posted by thmm View Post
    @OP,

    did you write the C++ code or did you find it somewhere ?
    This cpp reverseString is just my solution for some codewars.com kata, and the benchmark part is improvised for testing perf against some other solutions using godbolt, so may be not working in your env.


    What I still don't understand is the relation between char* and char[] in c, how am I supposed to run function with char* parameter and return the actual string and not pointer to the object that will be dead soon?

    I mean i can't do:
    Code:
    char[] function(char* string) { return string }
    and even if I could it would be still just a pointer to a dead object, I want to take a parameter of a string and return a string from a function without knowing the string size.

    Idk, maybe I shouldn't just touch old c, it feels kinda like not for human beings

  5. #5
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    Just for info, your C++ version could be as simple as:
    Code:
    std::string reverse(const std::string& str)
    {
        return std::string(str.rbegin(), str.rend());
    }
    Might be a good idea to focus on C++. It's more powerful and you don't need to know about pointers.

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char *strrev( char *str )
    {
      char *p, *endp;
    
      p = str;
      endp = p + strlen( str ) - 1;
    
      while ( endp > p )
      {
        char tmp;
    
        tmp = *endp;
        *endp-- = *p;
        *p++ = tmp;
      }
    
      return str;
    }
    
    int main( void )
    {
      char *s = "deadbeef";
      char *p;
    
      puts( s );
    
      p = strdup( s );
      strrev( p );
      puts( p );
    
      free( p );
    }

  7. #7
    Registered User
    Join Date
    Oct 2019
    Posts
    82
    Or..... :

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    
    static char *reverse(char *str)
    {
    	int length = strlen(str);
    	char *tmp;
    	char *result = tmp = malloc(strlen(str) + 1);
    
    
    	for (int i = length - 1; i >= 0; i--)
    	{
    		*result++ = str[i];
    	}
    
    
    	*result = '\0';
    
    
    	printf("%s \n", tmp);
    
    
    	return tmp;
    }
    
    
    
    
    int main(int argc, char *argv[])
    {
    	char *to_reverse = "This is the string to reverse";
    
    
    	char *reversed = reverse(to_reverse);
    
    
    
    
    	printf("%s \n", reversed);
    
    
    	return 0;
    }

  8. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Notice the routine strrev_, below, doesn't need to scan for the string length:
    Code:
    #define swap( a, b ) { typeof(a) t; t = (a); (a) = (b); (b) = t; }
    
    static char *strrev_( char *p, size_t size )
    {
      char *str = p;
      char *endp = p + size - 1;
    
      // scans only half of the buffer.
      while ( endp > p )
      {
        swap( *endp, *p );
        endp--; p++;
      }
    
      return str;
    }
    
    #define strrev( str ) strrev_( (str), strlen( (str) ) )
    
    // 'a' from 'allocated'.
    char *strreva( char *str )
    {
      char *p;
    
      p = strdup( str );
      if ( p != NULL )
        return strrev( p );
      return p;
    }
    
    char *strrev2( char **dst, char *src )
    {
      return *dst = strreva( src );
    }
    Needless to say this won't work for multibyte charsets like UTF-8.
    Last edited by flp1969; 02-02-2022 at 05:20 AM.

  9. #9
    Registered User
    Join Date
    Oct 2019
    Posts
    82
    Quote Originally Posted by flp1969 View Post
    Notice the routine strrev_, below, doesn't need to scan for the string length:
    Code:
    #define swap( a, b ) { typeof(a) t; t = (a); (a) = (b); (b) = t; }
    Well,.....

    Notice typeof is only available on some systems, probably GCC only?

  10. #10
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Quote Originally Posted by ghoul View Post
    Notice typeof is only available on some systems, probably GCC only?
    Works on GCC, CLANG and Intel C++... Any GOOD compiler. supports it.

  11. #11
    Registered User
    Join Date
    Oct 2019
    Posts
    82
    Quote Originally Posted by flp1969 View Post
    Works on GCC, CLANG and Intel C++... Any GOOD compiler. supports it.
    I was mostly talking about Microsoft compilers.

    But, well, anyways, you are right, nevermind.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reversing string
    By jsgn in forum C++ Programming
    Replies: 8
    Last Post: 05-16-2011, 07:10 AM
  2. reversing a string
    By swappo in forum C++ Programming
    Replies: 6
    Last Post: 06-14-2009, 03:18 PM
  3. Reversing a string
    By gandamkumar in forum C++ Programming
    Replies: 16
    Last Post: 11-27-2004, 10:09 PM
  4. Reversing a string
    By michelle1 in forum C++ Programming
    Replies: 12
    Last Post: 06-27-2003, 06:37 AM
  5. Reversing a String
    By ToasterPas in forum C++ Programming
    Replies: 10
    Last Post: 08-14-2001, 12:20 PM

Tags for this Thread