char **arr;
arr = (char **)calloc(1,sizeof(char*));
for(i = 0; i< 16; i++)
if(arr[i] = (char *)calloc(1, 2*sizeof(char)) == NULL)
perror("Memory cannot be allocated to arr[i]", %d);
The above code throws an error inside the for loop, when i am trying to allocate memory to arr[i]. Is anything wrong with this allocation. Essentially, i want to store 16 strings of length 2. I’ve tried it with array of pointers too (char *arr[16]). I have tried looking for resources on double pointer initializations using malloc() and calloc() and couldn’t find many . If you could point out some links, that would be greatly appreciated.
Thanks.
You need to allocate enough memory for 16 pointers, not just one.
What happens with your code is that
arrhas enough memory only for one pointer, soarr[0] = <something>is correct, butarr[1]and higher is touching memory that doesn’t belong to the program.Additionally, the way you assign the string pointers is wrong. You are assigning 0 or 1 values, depending on whether the result if
callocisNULL. You need to add parentheses there:Er even better: