初始化一个指针数组

时间:2014-10-01 13:54:03

标签: c++ arrays pointers

我想初始化一个指针数组。这是我的代码。它适用于较小的数字,即9979,但当我尝试动态初始化为66071时,它显示分段错误。现在我在另一个程序中,动态初始化了一个整数数组,大​​小为120007,工作正常,即没有分段错误。知道为什么这个错误发生在指针数组?可能是由于“dictnode”的结构大小?

struct dictnode{
    string word;
    int key;
    int code;
}; 
class LZW{
    dictnode **de_table; 
    int count_dec;
    int desize;

    public:
    LZW();
    //DECOMPRESSION
    void decompress();
    void storedictdec(string str1, string str2);
    void storedictdec1(string str1, string str2, int dec);
    bool checkdictdec(int n);
    void initialize_dec_dict();
    void printdictdec();
    int quadprobe(int k, int i);
};

LZW::LZW(){
    desize=66071;
    count_dec=0;
    de_table = new dictnode* [desize];

    for(int i=0; i<desize; i++){
        de_table[i]=NULL;
    }

    return;
}

4 个答案:

答案 0 :(得分:1)

我对这个简化的测试代码没有任何错误:

#include <string>

struct dictnode{
std::string word;
int key;
int code;
}; 

class LZW{
dictnode **de_table; 
size_t desize;
int count_dec;

public:
LZW();
~LZW();
};

LZW::LZW()
{
    desize=66071;
    count_dec=0;
    de_table = new dictnode* [desize];
    for(size_t i=0; i<desize; i++)
        de_table[i]=NULL;
}

LZW::~LZW()
{
    delete[] de_table;
}

int main()
{
    LZW *lzw = new LZW;
    delete lzw;
    return 0;
}

答案 1 :(得分:0)

我试过

#include <iostream>
using namespace std;

struct dictnode{
string word;
int key;
int code;

}; 

int main(int argc, char**argv) {
int desize=66071;
int count_dec=0;
dictnode** de_table = new dictnode* [desize];

for(int i=0; i<desize; i++){
    de_table[i]=NULL;
}

return 0;
}

一切顺利,valgrind回归:

==4036== Memcheck, a memory error detector
==4036== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4036== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==4036== Command: ./a.out
==4036== 
==4036== 
==4036== HEAP SUMMARY:
==4036==     in use at exit: 528,568 bytes in 1 blocks
==4036==   total heap usage: 1 allocs, 0 frees, 528,568 bytes allocated
==4036== 
==4036== LEAK SUMMARY:
==4036==    definitely lost: 528,568 bytes in 1 blocks
==4036==    indirectly lost: 0 bytes in 0 blocks
==4036==      possibly lost: 0 bytes in 0 blocks
==4036==    still reachable: 0 bytes in 0 blocks
==4036==         suppressed: 0 bytes in 0 blocks
==4036== Rerun with --leak-check=full to see details of leaked memory
==4036== 
==4036== For counts of detected and suppressed errors, rerun with: -v
==4036== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

请向我们展示此代码的全部范围

答案 2 :(得分:0)

现在看起来不错,但创建了一个析构函数来删除de_table:

LZW::~LZW(){
    delete[] de_table;
    return;
}

答案 3 :(得分:0)

您可能需要增加程序可用的堆量(这由链接器控制)。程序不会自动访问计算机中可用的所有内存。

您在什么操作系统上使用了什么编译器?