i asked a previous question on this website and it got answered using pseudo code, yet I still cant figure out how to properly solve this problem
basically i pass an array of characters, and a number that the user selects that correlates to how many new characters to add to the array. I want to create a new array with size = the old array + the new number of characters to add, prompt user for the new chars, and then add it to the new array (with the old chars in it reallocated). I dont know how to do this! and am frustrated.
char * add(char * array, int num)
{
/* malloc new_size bytes and assign to new_array
memcpy old_size bytes from old_array into the new_array
add additions into new_array starting from (new_array+old_size)
free the old_araray
return new_array;
*/
}
You tagged the question “realloc” so presumably you’re aware of the
realloc()function. It’d be simpler, and possibly more efficient, to use that instead ofmalloc(),memcpy(), andfree()What I don’t see here, though, is how the function knows the size of the “old” array. Is it a null-terminated string? If not, you’ll need to pass another integer that says how big the existing array is.
Assuming it’s a null-terminated string, you could do something like this:
If it’s not a null-terminated string, you’d pass in
old_lengthas an argument rather than determining it withstrlen(), don’t add 1 in therealloc()call, and don’t setstring[new_length]to a null at the end. The rest stays the same.