【发布时间】: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 &length不是那么C-ish。 -
C 中不能通过引用参数传递。
-
string的新值将在函数退出时丢失,并导致内存泄漏,并且传递的指针变量的值将(可能)不再有效。你可以有一个char **string,或者你可以给函数一个返回类型,比如char *strEscape。