1

Today I was told that I would be able to easily take the contents of a static array and copy the data over to the dynamically allocated one. I searched for a long while and still have not found a good explanation as to how and why that is possible. For example, if I have code as follows,

int i = 0;
char array[64];
for (; i < 64; ++i)
{
  array[i] = "a";
}

char* dynamicArray = (char*) malloc (sizeof (char*) * strlen (array));

I was told that I could take the contents of array, which in this case is an array of a's, and copy that data to my dynamic array. I am still confused as to how I can even do that, since functions like memcpy and strcpy have not been working with the static array. Is this copying situation possible? Thank you for the help, and I hope my explanation was okay.

1 Answer 1

3

Your code has a few issues:

array[i] = "a";

tries to assign a string (an array of characters) to a single char. You should use 'a' to define a single character.

char* dynamicArray = (char*) malloc (sizeof (char*) * strlen (array));

allocates memory but doesn't assign it. strlen(array) is also unsafe; strlen counts the number of characters until a nul terminator but array doesn't have one.

Your code should look something like

int i = 0;
char array[64];
for (; i < 63; ++i) {
  array[i] = 'a';
}
array[63] = '\0';
char* dynamicArray = malloc (strlen(array)+1); // +1 for nul terminator
strcpy(dynamicArray, array); // copy contents of array into dynamicArray
// use array
free(dynamicArray); // must have exactly one call to free for each call to malloc
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for explaining it along with comments. This helped a lot. Another question: if I were to use this method of copying in a function, then using it to insert the copied data into a list, is there a way to free the memory after insertion without loosing the inserted data?