C Notes

#include <stdio.h>
#include <string.h>
int main(void) {
    char f[] = "++++";
    char c;
    char m[11];
    int i;
    int o_size = 4;
    int i_size = 1;
    
    scanf("%c", &c);
    memset(m, c, 10);
    m[10] = 0;
    for (i = 0; i < 5; i++) {
        printf("%.*s%.*s%.*s\n", o_size, f, i_size, m, o_size, f);
        o_size -= 1;
        i_size += 2;
    }
    return 0;
}

e.g.: ends_with(filename, ".pdf.epub.mobi");

int ends_with(const char *string, const char *tail)
{
    const char *s1;
    const char *s2;
    if (!*tail)
        return 1;
    if (!*string)
        return 0;
    for (s1 = string; *s1; ++s1);
    for (s2 = tail; *s2; ++s2);
    if (s1 - string < s2 - tail)
        return 0;
    while (*--s1 == *--s2) { if (s2 == tail) return 1; } return 0;
}

faster bsearch:

int monobound_bsearch(uint8_t *key, Digest_t **array, size_t nmemb, size_t size, int (*cmp)(const void *, const void *))
{
    size_t mid, top, piv;
    int val;
    size_t base = 0;

    mid = top = nmemb;

    while (mid) {
        mid = top / 2;
        piv = base + mid;
        val = cmp(key, array[piv]->digest);

        if (val == 0) return piv;
        if (val >= 0) base = piv;
        top -= mid;
    }
    return -1;
}

https://gist.github.com/deltheil/5000725
qsort and bsearch:

#include <stdio.h>
#include <stdlib.h>

struct foo {
  int count;
  const char *misc;
};

typedef struct foo * pfoo;

struct foo *foo_new(int c, const char *m);
int foo_cmp(const void *a, const void *b);

int main() {
  /* Let's suppose we allocate a dynamic array with a given size */
  void **ary = malloc(3*sizeof(void *));
  ary[0] = foo_new(4, "mac");
  ary[1] = foo_new(1, "linux");
  ary[2] = foo_new(9, "windows");

  /* Sort by increasing `count`-s */
  qsort(ary, 3, sizeof(void *), foo_cmp);

  /* Now let's retrieve item by count (= search key) */
  struct foo f1 = {.count = 4};
  struct foo f2 = {.count = 7};

  /* bsearch key (1st param) must be of *same* type than array elements! */
  struct foo *pf1 = &f1;
  struct foo **res1 = bsearch(&pf1, ary, 3, sizeof(void *), foo_cmp);
  printf("search #1 (key = %d) -> %s\n", f1.count, res1 ? "found": "not found");

  struct foo *pf2 = &f2;
  struct foo **res2 = bsearch(&pf2, ary, 3, sizeof(void *), foo_cmp);
  printf("search #2 (key = %d) -> %s\n", f2.count, res2 ? "found": "not found");

  free(ary[0]);
  free(ary[1]);
  free(ary[2]);
  free(ary);

  return 0;
}

struct foo *foo_new(int c, const char *m) {
  struct foo *f = malloc(sizeof(*f));
  f->count = c;
  f->misc = m;
  return f;
}

int foo_cmp(const void *a, const void *b) {
  const pfoo *A = a;
  const pfoo *B = b;
  return ( (*A)->count - (*B)->count );
}

Popular posts from this blog

Dearpygui resizable table

mp3splt