Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Optimized version of leftpad in plain C

Name: Anonymous 2016-03-23 21:32

#include <string.h>

static const char*
string_add(const char* first, const char* second)
{
const char* result = malloc(strlen(first) + strlen(second) + 1);
strcat(result, first);
strcat(result, second);
return result;
}

const char*
leftpad(const char* str, size_t len, char ch)
{
int i = -1;

if (ch == 0) ch = ' ';

int len = strlen(str);

while (++i < len) {
char buf[2] = { 0 };
buf[0] = ch;
str = string_add(buf, str);
}

return str;
}

Name: Cudder !cXCudderUE 2016-04-02 16:31

>>42
+1

>>43,44,45
This is how those cargo cult "best practices" start. I wasn't saying "never use strlen", I was just saying use it when it makes sense and not when it doesn't. It didn't make sense to use strlen in that particular situation but that doesn't mean it doesn't make sense ever.

Now I feel like Dijkstra trying to explain how goto is not inherently bad...

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List