samedi 27 juin 2015

Array of chars to linked list - Using the address in array

i am trying to pass words from a string to a linked list, the thing is, i can't reallocate memory to my string inside my struct, i should be using the address of each word inside the array.

my struct:

typedef struct slist{
    char *string;
    struct slist * prox;
} *SList;

my function:

int words (char t[], SList *l){
    int i, p;
    p=0;
    *l = (SList) calloc(1, sizeof(struct slist));

    SList aux = NULL;


    SList li = *l;
    for(i=0; t[i]!='\0' ;){
        aux = (SList) calloc(1, sizeof(struct slist));

        li->string = &t[i];
        li->prox = aux;
        li = aux;

        while(t[i]!=' ') i++;

        //t[i++] = '\0'; -> this doesn't work, bus error 10;

        while(t[i]==' ') i++;

        p++; //This counts words
    }

    return p;

}

This works, kind of, my doubt is, i can't change the initial array to include a NULL char at the end of each word (Strings declared in C are read-only right?)

So, i tried to add the t[i]='\0' in vain.

At this moment, running the code with this string

char *str = "this is one sentence";

will get me the following strings in my linked list:

this is one sentence
is one sentence
one sentence
sentence

the expected result is not this one, it should add the NULL char after the first word inside my list->string

PS: The linked list is not well defined, it adds a NULL at the end unnecessarily but i can deal with that later on.

Thank you for your help!

Aucun commentaire:

Enregistrer un commentaire