[英]C++ Why does my recursion function return random characters or fail completely?
[英]Why does my array element retrieval function return random value?
我试图在C ++中实现自己的简单字符串实现。 我的实现不是\\0
分隔的,而是使用字符数组中的第一个元素(我选择用于实现字符串的数据结构)作为字符串的长度。
本质上,我将其作为数据结构: typedef char * arrayString;
作为一些原始字符串处理例程的实现,我得到了以下内容:
#include "stdafx.h"
#include <iostream>
#include "new_string.h"
// Our string implementation will store the
// length of the string in the first byte of
// the string.
int getLength(const arrayString &s1) {
return s1[0] - '0';
}
void append_str(arrayString &s, char c) {
int length = getLength(s); // get the length of our current string
length++; // account for the new character
arrayString newString = new char[length]; // create a new heap allocated string
newString[0] = length;
// fill the string with the old contents
for (int counter = 1; counter < length; counter++) {
newString[counter] = s[counter];
}
// append the new character
newString[length - 1] = c;
delete[] s; // prevent a memory leak
s = newString;
}
void display(const arrayString &s1) {
int max = getLength(s1);
for (int counter = 1; counter <= max; counter++) {
std::cout << s1[counter];
}
}
void appendTest() {
arrayString a = new char[5];
a[0] = '5'; a[1] = 'f'; a[2] = 'o'; a[3] = 't'; a[4] = 'i';
append_str(a, 's');
display(a);
}
我的问题是我的函数getLength()
。 我试图在Visual Studio中调试程序,并且一开始看起来一切都很好。
第一次在append_str()
函数内部调用getLength()
,它将为字符串长度(5)返回正确的值。 当在我自己的自定义字符串显示函数display()
调用它(以防止std::cout
引起的错误)时,它会正确读取值( 6
),但返回-42
? 这是怎么回事?
笔记
get_length()
,我必须执行first_element - '0'
因为否则,该函数将返回内部算术值的ascii值。 例如,对于十进制6
,它返回54
。 由于您得到的长度为return s1[0] - '0';
在getLength()
,应将length设置为newString[0] = length + '0';
而不是newString[0] = length;
一方面,为什么要在数组中存储字符串的大小? 为什么不使用某种整数成员来存储大小。几个字节确实不会受到损害,现在您的字符串长度可以超过256个字符。
您正在两个地方访问数组。
在append_str
for (int counter = 1; counter < length; counter++) {
newString[counter] = s[counter];
}
在您提供的示例中,起始字符串为“ 5foti”-不包含终止的空字符。 最大有效索引为4
。 在上面的函数中, length
已经设置为6
并且您正在访问s[5]
。
可以通过将for
语句中的条件更改为counter < length-1;
来counter < length-1;
并在display
。
int max = getLength(s1);
for (int counter = 1; counter <= max; counter++) {
std::cout << s1[counter];
}
同样,您在循环中通过使用counter <= max
来访问数组。
可以通过将for
语句中的条件更改为counter < max;
来counter < max;
这是一些改进,也应该涵盖您的问题:
int
,字符串数据本身应为char*
。 +
等。 - '0'
让我痛苦。 您从长度中减去了ASCII值42,但没有将其添加为字符。 此外,长度最大为127,因为char从-128变为+127。 参见第1点。 append_str
更改对象的指针。 这是非常糟糕的做法! 好的,谢谢大家的帮助。
问题似乎出在appendTest()
函数内部,在该函数中,我将要具有的值的字符代码存储为数组的第一个元素(即存储'5'
而不是5
)。 看来我没有编辑正确的先前代码,这就是导致我遇到问题的原因。
除了许多人问的问题之外, 为什么我不使用类或更好的设计 ,这是因为我想实现具有很多约束的基本字符串结构,例如没有类等。我基本上只想使用数组,而我所能提供的就是使它们动态分配,即可调整大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.