2009-04-12 123 views
0

我试图在数组中存储一个指针。多维数组(C++)

我的指针的指针是类对象是:

classType **ClassObject; 

,所以我知道我可以通过使用新的运营商像这样分配的:

ClassObject = new *classType[ 100 ] = {}; 

我读的文本文件,标点符号和这里是我到目前为止有:

// included libraries 
// main function 
// defined varaibles 

classType **ClassObject; // global object 
const int NELEMENTS = 100; // global index 


wrdCount = 1; // start this at 1 for the 1st word 
while (!inFile.eof()) 
{ 
    getline(inFile, str, '\n'); // read all data into a string varaible 
    str = removePunct(str); // User Defined Function to remove all punctuation. 
    for (unsigned x = 0; x < str.length(); x++) 
    { 
     if (str[x] == ' ') 
     { 
      wrdCount++; // Incrementing at each space 
      ClassObject[x] = new *classType[x]; 
     // What i want to do here is allocate space for each word read from the file. 

     } 
    } 
} 
// this function just replaces all punctionation with a space 
string removePunct(string &str) 
{ 
    for (unsigned x = 0; x < str.length(); x++) 
     if (ispunct(str[x])) 
      str[x] = ' '; 
    return str; 
} 

// Thats about it. 

我想我的问题是:

  • 我是否为文件中的每个单词分配了空间?
  • 我将如何将指针存储在我的while/for循环中的ClassObject数组中?
+0

你需要阅读http://stackoverflow.com/editing-help并重新格式化你的问题更具有可读性。 – lothar 2009-04-12 02:33:32

回答

3

如果您使用C++使用Boost Multidimensional Array Library

+0

你也应该看看这个问题:http://stackoverflow.com/questions/365782/how-do-i-best-handle-dynamic-multi-dimensional-arrays-in-cc/365800#365800 – Klaim 2009-04-12 12:06:37

1

嗯,我不知道你想做什么(尤其是新的* classType所[X] - 这是否甚至编译?)

如果你想为每一个字一个新classType所,那么你可以去

ClassObject[x] = new classType; //create a _single_ classType 
ClassObject[x]->doSomething(); 

提供ClassObject被初始化(如你所说)。

你说你想要一个二维数组 - 如果你想这样做,那么语法是:

ClassObject[x] = new classType[y]; //create an array of classType of size y 
ClassObject[0][0].doSomething(); //note that [] dereferences automatically 

不过,我也不能确定你的新* classType所是什么意思[100] = {}; - 那里的花括号是什么?现在看来似乎应该是

classType** classObject = new classType*[100]; 

我强烈建议你用别的东西,虽然,因为这是真的讨厌(而且你必须照顾删除...啊)

使用矢量<>或者如上面的帖子所示,增强库。

0

你的代码是完全正常的除外一行: ClassObject[x] = new *classType[x]; 星*需要走开,什么你可能想说的是,你要ClassObject要编制索引,字数而不是X。

替换该行: ClassObject[wrdCount] = new classType[x];

希望帮助, Billy3

+0

我试图将1个单词传递给构造函数,该构造函数接受一个const字符指针参数。除了那个,我可以调用每个函数。拥有ClassObject [] []。WhatIneed(cArray);不会工作 ClassObject [] []。WhatIdontNeed();作品 – user40120 2009-04-12 03:24:06