c - Using calloc() to set up char array, also "freeing" array when done -
c - Using calloc() to set up char array, also "freeing" array when done -
i'm trying set array of strings (in c, using linux). array hold 11 strings (static length). had array set as:
char answers[10][100];
but in code have portion calls fgets(input,sizeof(input),stdin). when fgets() portion called, final element of answers array beingness overwritten value of input (something answers' location on stack?). i'm trying "lock-in" memory utilize answers array. use
char answers=calloc(11*sizeof(char));
or
run through loop--
char answers[10]; for(c=0;c<=10;c++) { answers[c]=calloc(1*sizeof(char); }
also, i'll need utilize atexit() free allocated memory when i'm done... best way since can't pass arguments within atexit()?
atexit(free);
void free() { free(answers); }
thanks in advance!
okay, lots of misunderstandings, guess. pieces of code there in corrent. asked 11 strings so... char answers[10][100];
incorrect, should type char answers[11][100];
instead, reason why skipped input. mistakes... first - calloc()
has 2 parameters , not one, malloc()
, in next signature:
void *calloc(size_t nmemb, size_t size);
returns void*
area of memory allocated, first parameter number of elements you'd allocate , sec size of each element. second, typed above, returns pointer, void one, can't perform piece of code correctly:
char answers[10]; for(c=0;c<=10;c++) { answers[c] = calloc(11*sizeof(char)); }
what's problem ? first, parameters, said. sec fact made array of chars , not char pointers needed. should way:
char* answers[11]; //as requested 11 elements for(c=0;c<=10;c++) { answers[c] = (char*) calloc(1, my_str_length); }
when my_str_length constant of 100, shown in example. used casting upon void pointer, corrected utilize of calloc
, declaration of char pointers. code right - also, why utilize calloc
? there's no need in string. way, no need function when it's 1 line anyway. sec way declare this way:
char **answers = calloc(11, sizeof(char*)); for(i = 0 ; < 11 ; i++) { answers[i] = calloc(1, sizeof(char)*my_string_length); //basically my_string_length sizeof(char) one, it's there readability of code. }
this it, hope understand. read more memory allocation in c here:
about malloc()
about calloc()
about realloc()
c arrays free calloc atexit
Comments
Post a Comment