C 有没有更好的方法来编写这个函数?

C 有没有更好的方法来编写这个函数?,c,string,C,String,这是一个插入字符串函数 void ins( char * T, size_t ip, char * P) { char temp1[100], temp2[100]; strncpy(temp1,T,ip); strcpy(temp2, &T[ip]); strcat(&T[ip], P); strcat(&T[sizeof(temp1) + sizeof(P) - 2], temp2); } 有没有更好的方法来编写这个函数?

这是一个插入字符串函数

void ins( char * T, size_t ip, char * P)
{
    char temp1[100], temp2[100];

    strncpy(temp1,T,ip);
    strcpy(temp2, &T[ip]);

    strcat(&T[ip], P);
    strcat(&T[sizeof(temp1) + sizeof(P) - 2], temp2);
}

有没有更好的方法来编写这个函数?

我需要添加一个额外的参数
maxlen
:可以写入的str的最大大小。我还将返回类型修改为一些有用的内容

size_t do_insert(char *str, size_t maxlen, size_t where, char *ins)
{
    size_t len_str, len_ins;

    /* these could be arguments, too,
    ** if these are already known by the caller.
    */
    len_str = strlen(str);
    len_ins = strlen(ins);

    /* not enough space: return */
    if (len_str + len_ins >= maxlen)
        return len_str + len_ins;

    /* I don't know what should happen if the place to insert
    ** is beyond the length of str
    ** [ there also is a corner case lurking here if where == len_str]
    */
    if (where > len_str)
        return ???;

    /* make place for the insert by shifting str up.
    ** we move one byte extra: the nul character.
    */
    memmove( str + where + len_ins, str + where, len_ins + 1);

    /* put the insert where it belongs */
    memcpy ( str + where, ins, len_ins );

    /* return the length of the new string */
    return len_str + len_ins;
}

注意:未测试。

是,将类型放在参数列表上。是,通过给参数指定有意义的名称:)此函数应该做什么?是,不要溢出缓冲区,缩进函数体。LOL@indent-纳粹;我习惯于将无支撑的if()语句放在一行…
@indent-nazil
没有向我发送任何通知我更喜欢这两个行程序——判断它是否是()的
for要快得多或a
for()stmt,等等。