First, char *stuff_to_append_to[]
is an array of pointers of undetermined length, that is not a valid parameter, as the last dimension of an array must be specified when passed to a function, otherwise, pass a pointer to type.
Next, char **stuff_to_append
is a pointer to pointer to char and is completely valid, but given your use of stuff_to_append
within the function, it is obvious that is not what you intended.
If you wish to insert stuff_to_append
and truncate stuff_to_append_to
at the end of stuff_to_append
simply pass a pointer to each string as the argument. While int position
is fine, a choice of an unsigned value may be better as you will not insert at a negative array index.
Inside your function, you must validate there is sufficient space in stuff_to_append_to
to hold stuff_to_append
beginning at index position
(including space for the nul-byte)
With that in mind, you may want to do something like the following:
void append_this_stuff (char *stuff_to_append_to, char *stuff_to_append,
int position)
{
int somenumber = strlen (stuff_to_append),
lento = strlen (stuff_to_append_to),
end = position + somenumber;
if (end > lento) {
fprintf (stderr, "error: insufficient space in stuff_to_append_to.\n");
return;
}
for (int i = position; i < end + 1; i++) /* +1 to force copy of nul-byte */
stuff_to_append_to[i] = stuff_to_append[i - position];
}
You can write a small test program to confirm it’s operation, e.g.
#include <stdio.h>
#include <string.h>
...
int main (void) {
char stuff[] = "my dog has fleas!",
append[] = "cat has none!";
int pos = 3;
printf ("original: %s\n", stuff);
append_this_stuff (stuff, append, pos);
printf (" new: %s\n", stuff);
return 0;
}
Example Use/Output
$ ./bin/append
original: my dog has fleas!
new: my cat has none!
To do the same thing using pointer arithmetic instead of using array indexes, you can rewrite append_this_stuff
similar to the following:
void ats (char *to, char *from, int p)
{
if (p + strlen (from) > strlen (to)) {
fprintf (stderr, "error: insufficient space in stuff_to_append_to.\n");
return;
}
for (to += p; *from; to++, from++)
*to = *from;
*to = *from;
}
Lastly, if this lesson is not completely ingrained in your thought process, “Never post anything that you would not want in the hands of the recruiter as you interview for your first programming position.” The use of unprofessional or cute variable names, while it may express your frustrations, may not give the impression you want in the hands of another. Enough said.
2
solved Does this function I made correctly append a string to another string?