目前正在学习 C 中的内存管理,我目前遇到了在循环迭代时增加字符串长度的问题。
我试图找出逻辑上的方法是这样的:
// return string with "X" removed
char * notX(char * string){
result = "";
if(for int = 0; i < strlen(string); i++){
if (string[i] != 'X') {
result += string[i];
}
}
return result;
}
在其他语言中很简单,但在 C 中管理内存使其有点挑战性。我遇到的困难是当我使用 malloc 和 realloc 来初始化和更改我的字符串的大小时。在我目前尝试的代码中:
char * notX(char * string){
char* res = malloc(sizeof(char*)); // allocate memory for string of size 1;
res = ""; // attempted to initialize the string. Fairly certain this is incorrect
char tmp[2]; // temporary string to hold value to be concatenated
if(for int = 0; i < strlen(string); i++){
if (string[i] != 'X') {
res = realloc(res, sizeof(res) + sizeof(char*)); // reallocate res and increasing its size by 1 character
tmp[0] = string[i];
tmp[1] = '\0';
strcat(res, tmp);
}
}
return result;
}
请注意,我发现成功将结果初始化为一些大数组,例如:
char res[100];
但是,我想了解如何在不初始化具有固定大小的数组的情况下解决此问题,因为这可能会浪费内存空间或内存不足。
realloc
需要分配的字节数。size
为添加到 的每个字符递增res
。size + 2
用于提供正在添加的当前字符和终止零。
检查 的返回realloc
。NULL 表示失败。Usingtmp
允许返回res
ifrealloc
失败。
char * notX(char * string){
char* res = NULL;//so realloc will work on first call
char* tmp = NULL;//temp pointer during realloc
size_t size = 0;
size_t index = 0;
while ( string[index]) {//not the terminating zero
if ( string[index] != 'X') {
if ( NULL == ( tmp = realloc(res, size + 2))) {//+ 2 for character and zero
fprintf ( stderr, "realloc problem\n");
if ( res) {//not NULL
res[size] = 0;//terminate
}
return res;
}
res = tmp;//assign realloc pointer back to res
res[size] = string[index];
++size;
}
++index;//next character
}
if ( res) {//not NULL
res[size] = 0;//terminate
}
return res;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句