【问题标题】:Multi-Dimensional Array ( C++ )多维数组 (C++)
【发布时间】:2010-10-18 23:27:57
【问题描述】:

我正在尝试将指针存储在数组中。

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

classType **ClassObject;

所以我知道我可以像这样使用 new 运算符来分配它:

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 数组中存储一个指针?

【问题讨论】:

标签: c++ pointers multidimensional-array memory-management


【解决方案1】:

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

【讨论】:

【解决方案2】:

嗯,我不确定你想做什么(尤其是 new *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

但是,我也不确定你所说的 new *classType[ 100 ] = {}; 是什么意思。 - 花括号在那里做什么?好像应该是这样的

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

我强烈建议你使用其他东西,因为这真的很讨厌(而且你必须注意删除......呃)

使用矢量s 或如上述海报所建议的,boost 库。

【讨论】:

    【解决方案3】:

    您的代码非常好,除了一行: ClassObject[x] = new *classType[x]; 星号 * 需要消失,您可能想说的是您希望 ClassObject 被索引到 字数 而不是 x。

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

    希望对您有所帮助, 比利3

    【讨论】:

    • 我试图将 1 个单词传递给构造函数,它接受一个 const 字符指针参数。我可以调用除那个之外的所有函数。拥有 ClassObject[][].WhatIneed(cArray);不会工作 ClassObject[][].WhatIdontNeed();作品
    猜你喜欢
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2012-03-24
    相关资源
    最近更新 更多