Inserting characters in the middle of char array

后端 未结 5 1193
南方客
南方客 2021-01-23 03:51

I have a char array filled with some characters. Let\'s say I have \"HelloWorld\" in my char array. (not string. taking up index of 0 to 9)

What I\'m trying to do is ins

5条回答
  •  猫巷女王i
    2021-01-23 04:27

    The initial starting value for the inner loop is one short. It should be something like the following. Note too that since the characters are moved to the right, a new null terminator needs to be added:

        ch[strlen(ch) + 1] = '\0';
        for(j=strlen(ch); j>=i+2; j--) {  // note no "-1" after the strlen
    

    Edit As far as the "Is this a good way?" part, I think it is reasonable; it just depends on the intended purpose. A couple thoughts come to mind:

    • Reducing the calls to strlen might be good. It could depend on how good the optimizer is (perhaps some might be optimized out). But each call to strlen require a scan of the string looking for the null terminator. In high traffic code, that can add up. So storing the initial length in a variable and then using the variable elsewhere could help.
    • This type of operation has the chance for buffer overflow. Always make sure the buffer is long enough (it is in the OP).

提交回复
热议问题