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

ANY OF U REDDY 2 CHALLENGE ME YET?

Name: L. A. Calculus !!wKyoNUUHDOmjW7I 2013-06-20 0:33

CARN

Name: Anonymous 2013-06-20 14:19

>>42
Let's not forget that in a real program, we'll want to cleanup after ourselves. With the dynamic array, this is as simple as one free

array.c:
#include <stdio.h>
#include <stdlib.h>
#include "numelems.h"

int main() {
    int *a;
    int i;
    size_t n;
    unsigned long total;

    n = 1;
    a = malloc(n * sizeof(*a));
    for (i = 0; i < NUM_ELEMS; ++i) {
        while (n <= i) {
            n *= 2;
            a = realloc(a, n * sizeof(*a));
        }
        a[i] = i;
    }
    while (--i)
        total += a[i];
    printf("%lu\n", total);
    free(a);
    return 0;
}


With the linked-list, of course, you have free every node.

list.c
#include <stdio.h>
#include <stdlib.h>
#include "numelems.h"

typedef struct node {
    int n;
    struct node *next;
} node;

node *new(int n) {
    node *l;

    l = malloc(sizeof(*l));
    l->n = n;
    l->next = NULL;
    return l;
}

int main() {
    int i;
    unsigned long total;
    node *head;
    node *tail;

    head = NULL;
    for (i = 0; i < NUM_ELEMS; ++i) {
        if (head) {
            tail = tail->next = new(i);
        } else {
            tail = head = new(i);
        }
    }
    total = 0;
    tail = head;
    while (tail) {
        total += tail->n;
        tail = tail->next;
    }
    printf("%lu\n", total);
    while (head) {
        tail = head->next;
        free(head);
        head = tail;
    }
    return 0;
}


And let's see how this scales:
time ./array
49999995000000
./array  0.08s user 0.05s system 97% cpu 0.134 total
$ time ./list
49999995000000
./list  1.96s user 0.18s system 99% cpu 2.141 total


OUCH! Two seconds? You mean 10000000 mallocs and frees isn't BLINDING FAST?! Who would have thought?

``B-b-but, muh O(n) traversal.''
-- Lambda A. ``List Boy'' Calculus and his fag buddy

List: O(n) traversal, O(n) allocation, O(n) deallocation, O(n) access.
Array O(n) traversal, O(sqrt n) allocation, O(1) deallocation, O(1) access.

List: non-primitive, requires struct, optional auxiliary functions, etc.
Array: native to C, just declare and use it, fast as FUCK.

Time to the Standard again, Lambda. Maybe work out some Project Euler problems until you understand how to write non-shitty, non-slow, non-bloated, non-standard code.

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