mercredi 5 août 2015

How to create a dynamic array of strings with the space just necessary for each string in C


I want to have an array of pointers to strings,and just get the space necessary for each string. I know malloc and getc are required but not familiar with the use of them.

Here is part of my code. It gives the error message "Segmentation fault" ....

char **allstrs;
char *one_str;
int totstrs=0,current_size= INITIALSIZE;

allstrs = (char **)malloc(current_size*sizeof(char*)); //dynamic array of strings
while(getstr(one_str)!=EOF){
    if(totstrs == current_size){
        current_size *=2;
        allstrs = realloc(allstrs, current_size*sizeof(char*));
    }
    strcpy(allstrs[totstrs],one_str);
    printf("String[%d] is : %s\n",totstrs,allstrs[totstrs]);
    totstrs ++;

}
free(allstrs);   //deallocate the segment of memory

return 0;

and the function getstr called

char c; 
int totchars=0, current_size=INITIALCHARS;

str = (char*)malloc(sizeof(char));
while(c!='\n'){
    c = getc(stdin);     
    if(c==EOF){
        return EOF;
    }

    if(totchars == current_size){
        current_size *=2;
            str = (char*)realloc(str,current_size*sizeof(char));
    }
        str[totchars] = c;  //store the newly-read character    
    totchars++;
}
str[totchars]='\0';   //at the end append null character to mark end of string

return 0;

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire