I am working on 2 different programs, but have the same problem for both. I have a char array (that doesn't hold meaningful text) that I use for drawing things on the screen. The first one is for a race line that shows progress, and the other one for the map of an area that can be modified.
What I want to do is overwrite a section of the array, not the entire array, without changing the array's size. For example, if array1 looks like |..........| and I wanted to add a fallen tree at position 3 and a rock at position 10 it would change to |..-->>>..@|. What I meant in my title for 'specific' is that the amount of characters to be replaced is given by me or determined during execution, instead of calling a function that automatically knows when to stop.
I thought of doing it with a for loop, like:
char tree[5] = "-->>>";
char map[12] = "|..........|";
int offset = 3; //position from which to start replacing characters
object_size = sizeof(tree) / sizeof(char); //to get the length of the object to be added
for (int i = 0; i < object_size; i++) {
map[offset + i] = tree[i];
}
Is there a cleaner way to do it? I'm sure there must already be a function that does it, but most of what I find is in other languages. The idea is to then be able to use a 2-dimensional array to store the map and modify bigger areas.
mapstring indeed is a regular C string, you can use a straightstrncpy. This will copy the string in position, without the terminating zero. (Note that../sizeof(char)is redundant, assizeof(char) == 1per the C specifications.)char tree[5] = "-->>>";oups, where is the place for the terminating null??? It should bechar tree[6] = "-->>>";orchar tree[] = "-->>>";to let the compiler count for you.array1, tree,map, offsetare all well behaved together, or should code be resilient to troublesome cases likeoffset > strlen(map)? Without a stated model of error handling - if any, "a cleaner way to do it" is moot.