C ++动态数组:类型为" void"的值不能用于初始化类型" int"的实体。

时间:2016-11-11 22:28:00

标签: c++ arrays pointers dynamic struct

我正在为学校开发一个C ++项目,程序将从文本文件中读取数字列表,将它们存储在动态数组中,然后将它们打印到另一个文本文件中。说实话,我对这个指针有点失落,我得到了错误"类型为" void"不能用于初始化类型" int""的实体。在我的主要源文件中。

Main.cpp(这是我收到错误的地方):

#include "dynamic.h"

int main
{
    readDynamicData("input.txt","output.txt");
}

dynamic.cpp(程序的骨架):

#include "dynamic.h"


void readDynamicData(string input, string output)
{
    DynamicArray da; //struct in the header file
    da.count = 0;
    da.size = 5; //initial array size of 5

    int *temp = da.theArray;
    da.theArray = new int[da.size];


    ifstream in(input);
    ofstream out(output);

    in >> da.number; //prime read
    while (!in.fail())
    {
        if (da.count < da.size)
        {
            da.theArray[da.count] = da.number;
            da.count++;
            in >> da.number; //reprime
        }
        else grow; //if there are more numbers than the array size, grow the array
    }


    out << "Size: " << da.size << endl;
    out << "Count: " << da.count << endl;
    out << "Data:" << endl;
    for (int i = 0; i < da.size; i++)
        out << da.theArray[i];

    in.close();
    out.close();

    delete[] temp;
}


void grow(DynamicArray &da) //this portion was given to us
{
    int *temp = da.theArray;
    da.theArray = new int[da.size * 2];
    for (int i = 0; i<da.size; i++)
        da.theArray[i] = temp[i];
    delete[] temp;
    da.size = da.size * 2;
}

和dynamic.h,头文件:

#include <iostream>
#include <string>
#include <fstream>
#ifndef _DynamicArray_
#define _DynamicArray_


using namespace std;

void readDynamicData(string input, string output);

struct DynamicArray
{
    int *theArray;
    int count;
    int size;
    int number;
};

void grow(DynamicArray &da);

#endif

2 个答案:

答案 0 :(得分:0)

main是一个函数,因此它需要括号:

int main(){
    // your code
    return 0; // because it should return intiger
}

和。您的grow也是一个函数,因此如果您想调用它,则需要编写grow(),并且需要DynamicArray作为参数。

不可能在 C / C ++ 上编写任何不了解基本语法的编程语言的工作程序。

答案 1 :(得分:0)

你必须在main或任何函数中添加括号:

int main(){/*your code here ...*/};

2-你正在使用一个单一化的对象:

DynamicArray da; //struct in the header file
da.count = 0;
da.size = 5; //initial array size of 5

so int * theArray是一个成员数据,未初始化,欢迎使用段错误

da的所有成员都没有初始化,所以在使用之前你必须这样做。

3-你也可以为增长函数添加括号:

else grow(/*some parameter here*/); // grow is a function
头文件中的

4- using namespace std;是一种非常糟糕的做法。 提示在源内使用它

5-为什么在包含守卫之前包含iostream和string .. 纠正它:

#ifndef _DynamicArray_
#define _DynamicArray_

#include <iostream>
#include <string>
#include <fstream>

/*your code here*/

#endif