【问题标题】:Function to put ' ' after n symbols在 n 个符号后放置 ' ' 的函数
【发布时间】:2020-07-13 10:16:43
【问题描述】:

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

void strEscape(char* string, int length,int param) {
    int count = 0; // tried to count how many times , inserted ' '
    for (int i = 1; i + count < length; i++) {
        if (i%param==0) { // checking if reached n position
            length++;
            string = (char*)realloc(string, (length+1) * sizeof(char));
            for (int j = length; j > i; j--) {
                string[j] = string[j-1]; //swapping elements
            }

            string[i+count] = ' '; 
            string[length] = '\0';
            count++;
        }
    }

}

例如,假设我想把 ' ' 放在 3 个符号之后,所以 param = 3;

这就是我现在拥有的结果

输入->输出:

abca->abc a

abcabca-> abc abc a

abcabcabca -> abc abc abb aa -> 这里 smth 出错了

如果字符串包含 10 个或更多元素,我有一个 (HEAP[Source.exe]: Invalid address specified to RtlValidateHeap)

【问题讨论】:

  • 请通过minimal reproducible example 证明您的问题。
  • 这个int &amp;length 不是那么C-ish。
  • C 中不能通过引用参数传递。
  • string 的新值将在函数退出时丢失,并导致内存泄漏,并且传递的指针变量的值将(可能)不再有效。你可以有一个char **string,或者你可以给函数一个返回类型,比如char *strEscape

标签: c arrays string dynamic


【解决方案1】:

你可以这样做。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多