Dynamically allocated string arrays in C -
i'm trying understand how dynamically allocated arrays work in c 99. anyways, have following code:
int main() { char** members=malloc(4*sizeof(*members)); *members=malloc(5); *members="john"; *(members+1)="shouldn't work"; printf("%s \n",*members); printf("%s",*(members+1)); return 0; }
i thought run time error because didn't allocate (members+1), did print both "john" , "shouldn't work", also, apperas the *members=malloc(5) line wasn't necessary. why?
your assignments aren't doing think they're doing. when assign *members
or *(members+1)
, you're assigning char*
each string literal, not copying allocated (or not allocated) heap memory.
if instead replaced assignments strcpy
, i.e.:
strcpy(*members, "john"); strcpy(*(members+1), "shouldn't work");
then access violation on second assignment not first. likewise, reason malloc(5)
appears unnecessary because reassign pointer point string literal, instead of copying "john" string allocated memory.