structures/pointers help

I have been going around and around with this code. It may be that I just dont have a firm grasp on how everything works. Could anyone help me identify why this doesnt work? I know its a logical error, but dont know what it is.

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
#include<iostream>
using namespace std;

struct student {
    char *firstName;
    char *lastName;
    char *letterGrades;
    float *units;
    int numGrades;
};

void test(struct student *array) {
     int i=0;
     char blah[] = "Hello";
    array[i].firstName = new char[30];
    array[i].firstName = blah;
}

int main() 
{
    struct student test1[50];
    test(test1);
    cout << test1[0].firstName;
    cin.get();
    return 0;
}


thanks in advance for any help!
It does not work because the array blah is local to the function test(). When the function ends, the array no longer exists, and the accessing the pointer to its first element stored in firstName is an error

Consider actually using C++:

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>
#include <string>
#include <vector>
using namespace std;

struct student {
    string firstName;
    string lastName;
    vector<char> letterGrades;
    vector<float> units;
};

void test(vector<student>& array) {
    int i = 0;
    array[i].firstName = "Hello";
}

int main() 
{
    vector<student> test1(50);
    test(test1);
    cout << test1[0].firstName;
    cin.get();
}
Thank you! I understand now why it doesnt work! Your awesome! I ended up using strcpy() to just copy the information over to the new dynamically allocated variable, which gave me the result I was looking for.

thanks again!!
Topic archived. No new replies allowed.