Advertisement
NandanSinceBB

Cursed string reversal in C

Apr 22nd, 2025
972
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | Source Code | 0 0
  1. /*
  2. ============================================================
  3.   String reversal challenge but it's cursed
  4. ============================================================
  5.  
  6. Write a function that reverses a null-terminated string in-place, but with a few constraints :
  7.     1. You only get a single char*, which is initially at the start of the string.
  8.     2. No extra variables can be declared. You only have your one blessed char*.
  9.     3. No std functions.
  10.     4. You can only write helper functions that take a single char** to your blessed char*.
  11.  
  12. ============================================================
  13. */
  14.  
  15. #include <stdio.h>
  16.  
  17. // helpers
  18.  
  19. void swapWithNext(char** ptrRef)
  20. {
  21.     (*ptrRef)[0] = (*ptrRef)[0] + (*ptrRef)[1];
  22.     (*ptrRef)[1] = (*ptrRef)[0] - (*ptrRef)[1];
  23.     (*ptrRef)[0] = (*ptrRef)[0] - (*ptrRef)[1];
  24. }
  25.  
  26. void rewindToStart(char** ptrRef)
  27. {
  28.     (*ptrRef)--;
  29.     for( ; **ptrRef >= 0; (*ptrRef)--) {}
  30. }
  31.  
  32. void markEnds(char** ptrRef)
  33. {
  34.     **ptrRef *= -1;
  35.  
  36.     for( ; (*ptrRef)[1] != '\0'; (*ptrRef)++) {}
  37.     **ptrRef *= -1;
  38.    
  39.     rewindToStart(ptrRef);
  40. }
  41.  
  42. void leftShiftTillEndCh(char** ptrRef)
  43. {
  44.     swapWithNext(ptrRef);
  45.     **ptrRef *= -1;
  46.     (*ptrRef)++;
  47.     **ptrRef *= -1;
  48.  
  49.     while(1)
  50.     {
  51.         swapWithNext(ptrRef);
  52.  
  53.         if(**ptrRef < 0)
  54.         {
  55.             break;
  56.         }
  57.  
  58.         (*ptrRef)++;
  59.     }
  60.  
  61.     rewindToStart(ptrRef);
  62. }
  63.  
  64. // the actual function
  65. void cursedReverse(char* ptr)
  66. {
  67.     if(ptr[0] == '\0')
  68.     {
  69.         return;
  70.     }
  71.  
  72.     if(ptr[1] == '\0')
  73.     {
  74.         return;
  75.     }
  76.  
  77.     markEnds(&ptr);
  78.  
  79.     while(1)
  80.     {
  81.         if(ptr[0] < 0 && ptr[1] < 0)
  82.         {
  83.             swapWithNext(&ptr);
  84.             ptr[0] *= -1;
  85.             ptr[1] *= -1;
  86.             break;
  87.         }
  88.  
  89.         leftShiftTillEndCh(&ptr);
  90.     }
  91. }
  92.  
  93. // test
  94. void main(int argc, char* argv[])
  95. {
  96.     cursedReverse(argv[1]);
  97.     printf("%s", argv[1]);
  98. }
Tags: Cursed C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement