Declaring Array of Pointers structs type

Apr 2, 2011 at 1:10pm
There is no error while compiling but there is a run time error anyone knows why?

#include<iostream>
using namespace std;
struct StrCar{
char RegCode[10];
int PhoneNo;
char Colour[10];
int Model;
};
int main(){
StrCar *Car[1]={0}; //declaring array of pointers

cout<<"enter1:"<<endl;

cin.getline(Car[0]->RegCode,10);

cout<<"you entered"<<endl;

cout<<Car[0]->RegCode<<endl;

system("pause");
return 0;
}
Apr 2, 2011 at 1:24pm
closed account (zwA4jE8b)


StrCar *Car; //Declares a pointer to type struct
Car = new StrCar[1]; //now 'Car' points to an array of structs
Last edited on Apr 2, 2011 at 1:24pm
Apr 2, 2011 at 1:27pm
closed account (zwA4jE8b)
when using dynamic arrays, you must declare a pointer to the base address, then use the new keyword to allocate [x*sizeof(datatype)] number of bytes on the heap.

so in your case, you need StrCar *Car; so you have a variable pointing to the datatype StrCar,
and the Car = new StrCar[1]; to allocate enough memory on the heap to store 1 car struct. and by setting your pointer '=' to the newly allocated memory space on the heap, you can now access it.
Last edited on Apr 2, 2011 at 1:30pm
Apr 2, 2011 at 1:46pm
closed account (zwA4jE8b)
Also you need to use '.' not '->'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace std;

struct StrCar
{
	char RegCode[10];
	int PhoneNo;
	char Colour[10];
	int Model;
};

int main(){
	StrCar *Car;
	Car = new StrCar[6];


	cout<<"enter1:"<<endl;

	cin >> Car[0].RegCode;

	cout<<"you entered"<<endl;

	cout<<Car[0].RegCode<<endl;

	system("pause");
	return 0;
}



this code runs just fine
Last edited on Apr 2, 2011 at 1:48pm
Apr 2, 2011 at 2:00pm
closed account (zwA4jE8b)
This also works, originally you did not declare an array of pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <iomanip>

using namespace std;

struct StrCar
{
	char RegCode[10];
	int PhoneNo;
	char Colour[10];
	int Model;
};

int main(){
	StrCar **Car;                  //Pointer to pointer or type StrCar
	Car = new StrCar *[10];  //Declares array of pointers
	Car[0] = new StrCar;      //Initializes car[0] only

	cout<<"enter1:"<<endl;

	cin  >> Car[0]->RegCode;

	cout<<"you entered"<<endl;

	cout<<Car[0]->RegCode<<endl;

	system("pause");
	return 0;
}
Apr 3, 2011 at 2:22am
clear explanation... pointers are little bit complicated for starting thanks guys
Last edited on Apr 4, 2011 at 1:48pm
Topic archived. No new replies allowed.