How to overwrite part of a string in C?

  • A+
Category:Languages

I have for instance a string. And I only want to change the beginning few characters of the string and leave the rest as they are. What is the best way to do this in C?

#include <stdio.h> #include <string.h>  int main() {     char src[40];     char src2[40];     char dest[12];      memset(dest, '/0', sizeof(dest));     strcpy(src, "This is a string");     strcpy(src2, "That");     strncpy(dest, src, sizeof(src));     strncpy(dest, src2, sizeof(src2));      printf("Final copied string : %s/n", dest); } 

I would like the string to be changed from "This is a string" to "That is a string".

Is there an easy way to accomplish this that I am missing?

 


There are a few issues here.

First, dest is only 12 bytes long, which is too short to hold "This is a string". Trying to copy that string into dest will overrun the buffer. This invokes [undefined behavior}(https://en.wikipedia.org/wiki/Undefined_behavior). Make it at least 20 bytes.

Second sizeof(src) gives you the size of the whole array, which is 40, not the length of the string. This will also give undefined behavior if the destination buffer is not big enough. Use strlen instead. The same goes for sizeof(src2).

With those changes, you should have this:

#include <stdio.h> #include <string.h>  int main() {     char src[40];     char src2[40];     char dest[20];      memset(dest, '/0', sizeof(dest));     strcpy(src, "This is a string");     strcpy(src2, "That");     strncpy(dest, src, strlen(src));     strncpy(dest, src2, strlen(src2));      printf("Final copied string : %s/n", dest); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: