[b]initialisation of members of structures in a dynamic array ??

Apr 21, 2014 at 9:58am
initialisation of members of structures in a dynamic array ??
[/b]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
struct exam
{
	char name[15];
	int roll;
	double grade;
};

int main()
{
	
	exam * p = new  exam[3];
	
        \\ how should i initialise the structure members??
	
	

	
	
	cin.get();
}


Last edited on Apr 21, 2014 at 10:30am
Apr 21, 2014 at 10:22am
C++ string literals are arrays of const char, so you can't legally modify them.
Change name to be a const char pointer and it should work.


Well if you don't want to change the type of "name" then you should initialise it as you would an array for characters... i think the way you intialised the other members were fine

Edit:
you can use brace syntax to intialise the name only in C++0x. Otherwise you will have to use a for loop to assign each letter manually
Last edited on Apr 21, 2014 at 10:52am
Apr 21, 2014 at 10:37am
how should i initialise the structure members??


1
2
3
4
5
6
std::strcpy(p[0].name, "mjatt");
p[0].roll = 5;
p[0].grade = 2.7;
std::strcpy(p[1].name, "Void life");
p[1].roll = 8;
...


Apr 21, 2014 at 10:42am
thanks @ Peter87

By the way , what is wrong with this;

p[0].name = "mjatt";
Apr 21, 2014 at 10:45am
The problem is that you can't assign arrays like that. That's one of the reasons why we often prefer to use std::string instead of raw arrays to store text. If you change the type of exam::name to std::string you will be able to to do it exactly as you wrote it.
Apr 21, 2014 at 11:41am


thnx @ Peter87
@ Void life
Last edited on Apr 21, 2014 at 12:00pm
Topic archived. No new replies allowed.