Skip to content

Instantly share code, notes, and snippets.

@dpyro
Last active March 3, 2017 00:02
Show Gist options
  • Save dpyro/7fd39af27d30bddaed884b09a9ecf639 to your computer and use it in GitHub Desktop.
Save dpyro/7fd39af27d30bddaed884b09a9ecf639 to your computer and use it in GitHub Desktop.
in-place reverse of a null-terminated string
#include <string.h>
// In-place reverse a null-terminated string.
// Note: The behavior is undefined if str is not null-terminated.
void strrev(char* str) {
size_t n = strlen(str);
char *end = &str[n-1];
char tmp;
while (str < end) {
tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
if (argc <= 1) {
const char* name = argv[0] ? argv[0] : "strrev";
fprintf(stderr, "Usage: %s string\n", name);
exit(EXIT_FAILURE);
}
for (size_t i = 1; i < argc; i++) {
char* str = argv[i];
strrev(str);
fputs(str, stdout);
if (i < argc-1) {
fputs(" ", stdout);
}
}
fputs("\n", stdout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment