循环动态内存分配C ++

时间:2013-06-13 10:09:03

标签: c++

我在使用malloc为家庭作业分配使用for循环分配内存时遇到了问题。下面是我的构造函数的代码,它接受一个char数组和一个char指针数组,并返回char数组中的标记数。

构造函数应该遍历char数组,跳到第一个非空的字符(第一个标记的开头),然后打印该char的索引。然后它应该在字符串中找到下一个空字符(令牌的结尾),并打印其索引。执行此操作后,它会计算令牌中的字符数,并使用malloc在指针数组中分配内存。我被告知我的教授使用memcpy将令牌复制到指针数组中。然后程序打印指针数组。这是代码

#include <iostream>
using namespace std;


int parseCommandLine(char cline[], char *tklist[])
{
    int lineLength = strlen(cline);
    int tknCount = 0;
    int tknStart;
    int tknEnd;
    int tknLength;
    int tknIndex;
    bool check;
    cout<<cline<<":"<<lineLength<<endl;
    if(cline[0]==0)
    {
        check = false;
    }
    else
    {
        check = true;
    }
    for(int j=0; j<=lineLength; j++)
    {
        if (isspace(cline[j]) == false && check==false)
        {
            cout<<j<<endl;
            check = true;
            tknStart = j;
        }

         else if(j==0 && check==true)
        {
            cout<<j<<endl;
            tknStart = j;
        }
        else if (check==true && (isspace(cline[j]) || j==lineLength))

        {
            cout<<--j<<endl;
            check = false;
            tknCount++;
            tknIndex = tknCount - 1;
            tknEnd = j;
            tknLength = tknEnd-tknStart;
            tklist[tknIndex] = (char *) malloc(tknLength +1);
            memcpy(tklist + tknIndex,cline + tknStart, tknLength);
            cout<<tklist<<endl;
         }
    } 
    cout<<"There are "<<tknCount<<"tokens in this line.\n"<<endl;
    tknCount = 0;
    return tknCount;
}

运行构造函数时,它正确识别标记的端点,但它只打印第一个内存位置,这使得看起来好像malloc不接受循环。这很奇怪,请尽可能帮忙。

修改:根据评论,这是一个简单的main()

int main ()
{
    char * out[6] = {0};
    char cline[] = "new_sensor_node SN42 42 3.57 5.0 7";
    parseCommandLine(cline, out);
    return 0;
}

以下是运行此命令的输出:

$ ./a.out 
new_sensor_node SN42 42 3.57 5.0 7:34
0
14
0x7fffd3762c70
16
19
0x7fffd3762c70
21
22
0x7fffd3762c70
24
27
0x7fffd3762c70
29
31
0x7fffd3762c70
33
33
0x7fffd3762c70
34
There are 6tokens in this line.

请注意,每次迭代都会打印相同的地址。

根据要求,这是输入代码

ifstream infile;
char line[MAX_CMD_LINE_LENGTH] = {0};
char *tokenList[MAX_TOKENS_ON_A_LINE];

int main()
{
infile.open("p4input.txt", ios::in);
if(infile.fail())
{
    cout<<"The input file has failed to open. Program will now terminate."<<endl;
    return 0;
}
else
{
    infile.getline(line,MAX_CMD_LINE_LENGTH);
    parseCommandLine(line, tokenList);
    system("pause");
    return 0;
}
}

标题

#define MAX_CMD_LINE_LENGTH 256
#define MAX_TOKENS_ON_A_LINE 30

1 个答案:

答案 0 :(得分:0)

tklist是一个指针数组。在线

tklist[tknIndex] = (char *) malloc(tknLength +1);

您正在指定一个指向数组tklist[]元素的指针。 tklist本身没有改变!只为其元素赋值。 因此,当您执行cout<<tklist<<endl;时,tklist始终会打印它指向的地址。

主程序*tokenList上的另一件事未初始化,因此它指向一个任意地址(0x7fffd3762c70)。

我建议您在调用*tokenList之前在main()中为parseCommandLine(line, tokenList);分配一次内存,并且只在cout<<tklist+tknIndex<<endl;中打印parseCommandLine()

相关问题