c - Failing to access data from an array -


i reading file (each line wolds 1 word) , putting each line array. i'll segmentation fault whenever try access element in array. on appreciated. *update: added while loop grab character 1 one still segmentation fault

the pointer made here:

char* ptr; 

i passed through function this:

filldict(ptr,&size); int filldict(char* ptr,int *size) 

and reads file , puts array here:

    int = -1;     int numb;     int wsize;     while (fgets(word,30,file)!=null)     {             if (i==-1)             {                     if(word[strlen(word)-1]=='\n')                     {                             word[strlen(word)-1] = 0;                     }                     numb = atoi(word);                     ptr = malloc(sizeof(char));             }             else             {                     if(word[strlen(word)-1]=='\n')                     {                             word[strlen(word)-1] = 0;                     }                     wsize = wsize+strlen(word);                     ptr = realloc(ptr,wsize);                      int j = 0;                     //added here                     while(j<strlen(word)-1)                     {                             printf("%d\n",j);                             ptr[j] = word[j];      //crashes here                             j++;                     }                     ptr[j] = '\0';                 //to here                      size++;             }             i++;     }     printf("%s",ptr[0]);           //but fails here     fclose(file); 

as @jagannath mentioned, treating ptr variable 2 dimensional array.

in reality, allocate simple buffer.

schematically :

ptr = [][][][][][][][][][][][][][\0]; 

then, have word simple buffer follow :

word = [h][e][l][l][o][\0]; 

if want copy word ptr, need iterate on both buffers , copy character character follow :

word = [h][e][l][l][o][\0];         v  v  v  v  v ptr  = [h][e][l][l][o][][][][][][][][][\0]; 

otherwise, can create array of word creating 2 dimensional array.

 ptr = [|][|][][]...[\0]         v  v        [h][w]        [e][o]        [l][r]        [l][l]        [o][d]        [0][0] 

finally, have flaws in code. @ malloc(1)... , wsize never initialized, when wsize = wsize+strlen(word); behavior undefined.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -