【发布时间】:2011-05-05 05:13:03
【问题描述】:
我正在处理的一个家庭作业项目使用静态和动态数组。但是,我还没有实现动态数组,这是一个奇怪的差异,试图获取我的静态数组的长度。
我使用了一系列 cout 语句来尝试找出导致我出现分段错误的原因,因为这个过程看起来很简单。我发现在我的驱动程序中,它正在计算正确的范围和长度,但是一旦我将数组传递给用户定义的类函数,在同一个数组上执行的相同语句会产生不同的结果。
我的驱动函数:
using namespace std;
#include <iostream>
#include "/user/cse232/Projects/project07.string.h"
int main()
{
const char string1[] = {'a', 'b', 'c', 'd', 'e', 'f'};
String test1();
cout << "Size of array: " << sizeof(string1) << endl;
cout << "Size of item in array: " << sizeof(char) << endl;
cout << "Length of array: " << (sizeof(string1)/sizeof(char)) << endl;
cout << "Range of array" << (sizeof(string1)/sizeof(char))-1 << endl << endl;
String test2(string1);
}
运行时,我从驱动程序获得以下输出:
Size of array: 6
Size of item in array: 1
Length of array: 6
Range of array5
我的支持文件:
/* Implementation file for type "String" */
using namespace std;
#include <iostream>
#include "/user/cse232/Projects/project07.string.h"
String::String( const char Input[] )
{
cout << "Size of array: " << sizeof(Input) << endl;
cout << "Size of item in array: " << sizeof(char) << endl;
cout << "Length of array: " << (sizeof(Input)/sizeof(char)) << endl;
cout << "Range of array" << (sizeof(Input)/sizeof(char))-1 << endl << endl;
/* Bunch of reallocation stuff that is commented out
for the time being, unimportant*/
}
String::~String()
{
Capacity = 0;
Length = 0;
Mem = NULL;
}
这是我从支持文件中得到的输出,
Size of array: 4
Size of item in array: 1
Length of array: 4
Range of array3
这显然是不对的。如果有帮助,这里是头文件(省略未实现的函数)。它是不可改变的:
/******************************************************************************
Project #7 -- Interface file for type "String"
******************************************************************************/
#ifndef STRING_
#define STRING_
using namespace std;
#include <iostream>
class String
{
private:
unsigned Capacity; // Number of memory locations reserved
unsigned Length; // Number of memory locations in use
char * Mem; // Pointer to memory to hold characters
public:
// Construct empty string
//
String()
{
Capacity = 0;
Length = 0;
Mem = NULL;
}
// Destroy string
//
~String();
// Construct string by copying existing string
//
String( const String& );
// Construct string by copying C-style character string
//
String( const char[] );
#endif
我最大的问题是为什么我得到两个单独的输出。第一个是我在分配内存时需要使用的;否则我会遇到分段错误。谁能给点建议?
【问题讨论】:
-
我测试过的另一件事是在我的支持文件中的 Input[0]、Input[1] 等处打印输入。它识别了 Input[5] = 'f' 但它计算的长度和范围与我的驱动程序文件中的数组不同,即使数组相等。
-
请注意,
String test1()确实不创建String对象。相反,它 forward 声明了一个返回String并且不接受任何参数的函数。你的意思可能是String test1;。
标签: c++ arrays segmentation-fault