您好,我的问题有点难以解释,所以我将在此处发布我的代码部分并通过示例解释问题。
这里的代码有一个大数组和一个小数组,其中大数组被分成小部分,存储在小数组中,小数组在屏幕上输出其内容。
然后我释放了小数组的分配内存,并用大数组的下一部分再次初始化它:
//this code is in a loop that runs until all of the big array has been copied
char* splitArray = new char[50];
strncpy(splitArray, bigArray+startPoint, 50); //startPoint is calculated with every loop run, it marks the next point in the array for copying
//output of splitArray on the screen here
delete splitArray;
//repeat loop here
现在我的问题是每次输出的字符串末尾都有一些随机符号。例如 "some_characters_here...last_char_hereRANDOM_CHARS_HERE".
在深入研究之后,我发现 splitArray 实际上的大小不是 50,而是 64,空终止符为 64。 所以当我从 bigArray 复制到 splitArray 时,在真正的字符串之后仍然有 14 个随机字符,当然我不想输出它们。
一个简单的解决方案是在 [50] 处的 splitArray 中手动设置空终止符,但程序无法再次删除该数组。
有人可以帮我找到解决方案吗?最好有一些示例代码,谢谢。
最佳答案
如果您只是设置splitArray[49] = 0
,程序如何“再次删除数组失败”?不要忘记,长度为 50 的数组的索引范围为 0 到 49。splitArray[50] = 0
正在写入为 splitArray
分配的内存之外的内存,所有带来的后果。
关于C++ 字符数组正确移动空终止符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293325/