Pointers and Vectors

Hi,
i have to solve the following exercise. Write a constructor for the class testArray which uses the "new" operator to assign anaraay of 10 integers to the int pointer IntArray. The constructor should have a single argument which is used to assign an initial value to each array element. The default value for the argument should be 10. Write a main() routine which declares a testArray object and uses the PrintData() funtion to print out its IntArray fiels.
this is the given class:

1
2
3
4
5
6
7
8
9
10
class testArray
{
private:
	int *intArray;
public:
	/// add constructor
	void PrintData();
};

#endif   


and the PrintData() function.

Here my solution.

testArray.h file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef TESTARRAY_H			
#define TESTARRAY_H
#include <vector>

class testArray
{
private:
	int *intArray;
public:
	testArray(int arg);
	void PrintData();
};

#endif 


testArray.cpp file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "testarray.h"
#include <iostream>
using namespace std;

testArray::testArray(int arg)
{
int *intArray= new int[10];
for (int i=0; i<10; i++)
	*intArray[i]=arg;
};

void testArray::PrintData()
{
for (int Index=0;Index < 10; Index++)
	cout << intArray[Index] << "\n";
};



1
2
3
4
5
6
7
8
9
10
11
12
13
main.cpp file
#include "testarray.h"
#include <iostream>
#include <conio.h>

int main()
{
int ch;
testArray obj1(10);
obj1.PrintData();
ch=getch();
return 0;
}


It gives me an error in testArray.cpp at the line
*intArray[i]=arg;

and in addition, in its PrintData() method the last line
cout << intArray[Index] << "\n";

i think it will print only the memory location of the pointer
but not the value because the pointer is not dereferenced.
Thank
Remove * from
*intArray[i]=arg;
oh, doesn t work. :)
in the testArray::testArray(int arg) constructor you are declaring a new temporary int* intArray instead of the using the class member
Topic archived. No new replies allowed.