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 of malloc()
, memcpy()
, and free()
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:
char *add(char *string, int num) {
// Note, these represent the length *without* the null terminator...
int old_length = strlen(string);
int new_length = old_length + num;
// ...so we add 1 here to make room for the null.
string = realloc(string, new_length + 1); // Error checking omitted
for (int n = old_length; n < new_length; n += 1) {
// Prompt for the new characters; here I'll just assume they're all 'X'.
char new_char = 'X';
string[n] = new_char;
}
string[new_length] = '\0';
return string;
}
If it's not a null-terminated string, you'd pass in old_length
as an argument rather than determining it with strlen()
, don't add 1 in the realloc()
call, and don't set string[new_length]
to a null at the end. The rest stays the same.