Saturday, 15 September 2012

c - Value of char array changes to second iteration value, I want it to be independent -



c - Value of char array changes to second iteration value, I want it to be independent -

i under impression on each run, in strings array, storing @ pos new str since declaring everytime, instead, on 2nd run if addstr become hello, , on first run hi, first run hi becomes hello. want different char array on each run in strings later on each position have different strings. requirements can not utilize malloc, realloc, calloc. thought on 2nd iteration of first loop creating on char str independent of previous one. please help me.

int pos = 0; for(i=0; i<4; i++) { if(file [i]=='a') { char str[5]; int b=0; for(b; b<3; bi++) { str[b]=file[b]; } strings[pos]=str; pos++; } }

when this:

strings[pos]=str;

it simply sets array element buffer pointed 'str'. not re-create string. 'str' buffer never changes, entire array ends pointing same buffer.

rather, @ line need re-create string. if can't utilize malloc, strings array needs have buffers @ each array element (aka 2 dimensional array). maybe declare like:

char strings[5][5];

then instead of using strcpy re-create 'str', re-create string 'strings[pos]';

c

No comments:

Post a Comment