Friday, 15 August 2014

c - Array of pointers to strings not storing data as it should -



c - Array of pointers to strings not storing data as it should -

i trying store words text file in dynamically assigned arrays of chars. using pointer arrays array of chars in order allocate memory dynamically reason stores lastly input word arrays of chars pointing to, though in places strings should not fit allocated space smaller strings.

here code:

#include <stdio.h> #include <stdlib.h> #include <string.h> int main () { char input_string[30]; int string_length, text_length; // calculating number of words in text file. text_length=0; freopen("in.txt", "r", stdin); while (scanf("%s", &input_string)!=eof) { text_length++; } freopen("con", "r", stdin); // dynamically assigning array of chars store words char **pointer; int i; pointer=(char*)calloc(text_length, sizeof(char)); freopen("in.txt", "r", stdin); (i=0;i<text_length;++i) { scanf("%s", &input_string); string_length = strlen(input_string); pointer[i]=(char*)calloc(string_length, sizeof(char)); *(pointer+i)=input_string; } (i=0;i<text_length;++i) { printf("%s ", *(pointer+i)); } freopen("con", "r", stdin); homecoming 0; }

*(pointer+i)=input_string

here input_string array , takes string file. in above statement, overwriting address of pointer array(allocated memory) input string.

pointer[i]=(char*)calloc(string_length, sizeof(char)); // alloacted memory

*(pointer+i)=input_string; //alloacted memory overwritten here pointer[i] , *(pointer+i) both both notifies same

so each index of array has same base of operations address of input_string , while de-refer give string nowadays in array(last string). reason problem. improve memcpy or strcpy.

pointer[i]=(char*)calloc(string_length, sizeof(char)); strcpy(pointer[i], input_string)

or

pointer[i]=(char*)calloc(string_length, sizeof(char)); memcpy(pointer[i], input_string, string_length)); ((pointer+i)+string_length)='\0'; /* assigning null character @ end of string * /

c arrays string pointers

No comments:

Post a Comment