gpt4 book ai didi

c++ - 为什么我的数组元素检索函数返回随机值?

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:17 25 4
gpt4 key购买 nike

我正在尝试用 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 中调试我的程序,一开始一切看起来都很好。

第一次调用 getLength() 时,在 append_str() 函数内,它返回正确的字符串长度值 (5)。当它在 display() 中被调用时,我自己的自定义字符串显示函数(以防止 std::cout 出现错误),它读取值 ( 6) 正确,但返回 -42?怎么回事?

enter image description here

注意事项

  1. 忽略我在代码中的注释。这纯粹是教育性的,我只是想看看什么级别的注释可以改进代码,什么级别会降低代码质量。
  2. get_length() 中,我必须执行 first_element - '0',否则函数将返回内部算术值的 ascii 值。例如,对于十进制 6,它返回 54
  3. 这是一项教育工作,所以如果您发现任何其他值得评论或修复的内容,请务必告诉我。

最佳答案

由于您在 getLength() 中将长度设置为 return s1[0] - '0'; 您应该将长度设置为 newString[0 ] = length + '0'; 而不是 newString[0] = length;

另一方面,为什么要将字符串的大小存储在数组中?为什么不使用某种整数成员来存储大小。几个字节确实不会造成伤害,现在您有一个长度可以超过 256 个字符的字符串。

关于c++ - 为什么我的数组元素检索函数返回随机值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29499451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com