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

How to expert code

Name: Anonymous 2011-10-04 10:19



    // Split
    // Creates array of char* pointers to tokens, seperated by 'c'
    // a is array, al is number of elements
    // returns true on success, false on fail.
    // if success,  called should free a[0] (the string), and "a" itself (the arrya of pointers)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int split(char *s, char c, char ***a, int *al) {
    char *ce = NULL; // current element
    char *ne = NULL; // next element
    char *p  = NULL;
    int  i   = 0;

    if(!s) {
        return -1;
    }

    // first pass: just count
    p = s;
    *al = 1;
    while(1) {
        p = strchr(p,c);
        if(!p) {
            break;
        }
        p++;
        (*al)++;
    }

    printf("count: %d\n",*al);

    // alloc our output
    *a = malloc(sizeof(char*)*(*al));

    // second pass actually splits
    s = strdup(s);
    ce = s;
    while(1) {
        ne = strchr(ce,c);
        if(ne) {
            *ne++ = 0;
        }
        (*a)[i] = ce;
        if(!ne) {
            break;
        }
        i++;
        ce = ne;
    }


    return 0;
}

int main(int argc, char **argv) {
    char**a = NULL;
    int n = 0;

    if(argc<3) {
        printf("args plz!\n");
        return 1;
    }

    split(argv[1],argv[2][0],&a,&n);

    int i;
    for(i=0;i<n;i++) {
        printf("a %02d: \"%s\"\n",i,a[i]);
    }

    return 0;
}

Name: Anonymous 2011-10-04 10:49

No deallocation. Trash code.

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