C 函数来放置'';在n个符号之后

C 函数来放置'';在n个符号之后,c,arrays,string,dynamic,C,Arrays,String,Dynamic,我需要写一个函数,每n个位置分配一个空字符。现在我有这样的smth,但它不是我想要的工作) void街景(char*string,int-length,int-param){ int count=0;//尝试计数多少次,插入“” 对于(int i=1;i+计数i;j--){ 字符串[j]=字符串[j-1];//交换元素 } 字符串[i+计数]=''; 字符串[长度]='\0'; 计数++; } } } 例如,假设我想在3个符号后加上“”,那么param=3 这就是我现在得到的结果 输入->输出

我需要写一个函数,每n个位置分配一个空字符。现在我有这样的smth,但它不是我想要的工作)

void街景(char*string,int-length,int-param){
int count=0;//尝试计数多少次,插入“”
对于(int i=1;i+计数<长度;i++){
如果(i%param==0){//检查是否到达n位置
长度++;
字符串=(char*)realloc(字符串,(长度+1)*sizeof(char));
对于(int j=长度;j>i;j--){
字符串[j]=字符串[j-1];//交换元素
}
字符串[i+计数]='';
字符串[长度]='\0';
计数++;
}
}
}
例如,假设我想在3个符号后加上“”,那么param=3

这就是我现在得到的结果

输入->输出:

abca->abca

abcabca->abca

abcabca->abc abb abb aa->这里出了问题


如果字符串包含10个或更多元素,则我有一个(HEAP[Source.exe]:指定给RtlValidateHeap的地址无效

void strEscape(char** pstr, int len, int param) {

    if(param <= 0 || param >= len) {
        return;
    }
    // required length of new string
    int new_len = len + (len-1)/param;

    // allocate memory for new string
    char* new_str = malloc(new_len * sizeof(char) + 1);

    int i = 0, j = 0;
    while(j < new_len) {
        if(i > 0 && i%param == 0) {
            new_str[j++] = ' ';
        }
        new_str[j] = (*pstr)[i];
        i++;
        j++;
    }
    new_str[j] = '\0';

    // free old string
    free(*pstr);
    // assign pstr to point to new string
    *pstr = new_str;
}

int main() {
    char* str = "abcdabcdabcd";
    // pstr is pointer to string str
    char** pstr = &str;
    strEscape(pstr, 12, 3);
    printf("%s\n", str);
    return 0;
}
void街景(字符**pstr,int len,int param){
如果(参数=len){
回来
}
//新字符串的所需长度
int new_len=len+(len-1)/param;
//为新字符串分配内存
char*new_str=malloc(new_len*sizeof(char)+1);
int i=0,j=0;
而(j0&&i%param==0){
新的_str[j++]='';
}
新的_str[j]=(*pstr)[i];
i++;
j++;
}
新的_str[j]='\0';
//自由旧弦
免费(*pstr);
//将pstr指定给指向新字符串
*pstr=新的_str;
}
int main(){
char*str=“abcdabcdabcd”;
//pstr是指向字符串str的指针
字符**pstr=&str;
街景(pstr,12,3);
printf(“%s\n”,str);
返回0;
}

请说明a的问题。此
int&length
不是C-ish.Pass by reference参数在C中是不可能的。函数退出时,
string
的新值将丢失,内存泄漏,并且传递的指针变量的值(可能)将不再有效。您可以有一个
char**string
,也可以给函数一个要返回的类型,例如
char*strEscape
void strEscape(char** pstr, int len, int param) {

    if(param <= 0 || param >= len) {
        return;
    }
    // required length of new string
    int new_len = len + (len-1)/param;

    // allocate memory for new string
    char* new_str = malloc(new_len * sizeof(char) + 1);

    int i = 0, j = 0;
    while(j < new_len) {
        if(i > 0 && i%param == 0) {
            new_str[j++] = ' ';
        }
        new_str[j] = (*pstr)[i];
        i++;
        j++;
    }
    new_str[j] = '\0';

    // free old string
    free(*pstr);
    // assign pstr to point to new string
    *pstr = new_str;
}

int main() {
    char* str = "abcdabcdabcd";
    // pstr is pointer to string str
    char** pstr = &str;
    strEscape(pstr, 12, 3);
    printf("%s\n", str);
    return 0;
}