gpt4 book ai didi

c++ - C++初始化后的神秘数组值

转载 作者:行者123 更新时间:2023-11-28 03:49:34 25 4
gpt4 key购买 nike

由于某种原因,桶数组的第一个元素的值被初始化为数组的大小,并在函数调用后增加大小。

头文件:

#ifndef TABLE
#define TABLE

#include <iostream>
#include <cstdlib>

typedef struct {
double successful , unsuccessful[2] ;
} Perform ;

using namespace std ;

template <class DATA>
class Table {
private :
DATA bucket[];
bool passbit[];
bool isFull[];
unsigned tableSize;
unsigned currentSize;
unsigned sProbes;
unsigned pbCount;

public :
explicit Table ( unsigned size = 5 ) ;
void clear ( ) ;
//bool insert ( DATA & data ) ;
bool insertD ( DATA & data ) ;
//bool fetch ( DATA & data ) const ;
bool getData ( unsigned i , DATA & data , bool & apassbit ) const ;
//Perform perform ( ) const ;
};

#endif

我现在只使用构造函数和一个函数,但我会包含所有内容。

#include <typeinfo>
#include <queue>
#include <iostream>

#include "table.hpp"

using namespace std ;

template <class DATA>
Table<DATA> :: Table ( unsigned size )
{
tableSize = size;
currentSize = 0;
sProbes = 0;
pbCount = 0;
bucket[tableSize];
cout << bucket[0] << "\n";
passbit[tableSize];
isFull[tableSize];
}

template <class DATA>
void Table<DATA> :: clear()
{
currentSize = 0;
sProbes = 0;
pbCount = 0;
for (int i = 0; i < tableSize; i++)
{
bucket[i] = 0;
passbit[i] = false;
isFull[i] = false;
}
}

template <class DATA>
bool Table<DATA> :: insertD ( DATA & data )
{
cout << bucket[0] << "\n";
unsigned value = unsigned ( data );
unsigned index = value % tableSize;
unsigned step = value % (tableSize - 2) + 1;
while ( isFull[index] && !(bucket[index] == data) )
{
passbit[index] = true;
pbCount++;
index -= step;
if ( index < 0 )
index += tableSize;
}
if ( isFull[index] && (bucket[index] == data) )
return false;
else
{
bucket[index] = data;
isFull[index] = true;
currentSize++;
return true;
}
}

template <class DATA>
bool Table<DATA> :: getData ( unsigned i , DATA & data , bool & apassbit ) const
{
if( bucket[i] != 0 )
{
data = bucket[i];
apassbit = passbit[i];
return true;
}
else
return false;
}

主要功能:

#include <iostream>
#include "table.cpp"
#include "table.hpp"

int main()
{
Table<int> table = Table<int>();
int i = 1;
int ii = 2;
int iii = 3;
int iv = 4;
int v = 5;
table.insertD(i);
table.insertD(ii);
table.insertD(iii);
table.insertD(iv);
table.insertD(v);
return 0;
}

输出:

5
5
261
65797
16843013
Segmentation fault

最佳答案

问题是您正在尝试初始化静态分配的数组。您需要使用动态分配的数组或声明静态分配的数组足够大以容纳您需要的所有数据。当然,既然你使用的是c++,你应该考虑使用STL vector 。

以下是您需要如何调整代码:

class SomeClass
{
private:
double* someArray;
int someArraySize;

public:
SomeClass( int arraySize )
{
someArray = new double[arraySize];
}

~SomeClass()
{
delete [] someArray;
}
};

这使用动态分配。请注意,当类实例被析构时,您需要删除该数组。

关于c++ - C++初始化后的神秘数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5972223/

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