我把代码提取了一下。希望大佬解惑。
file: TestStudent.cpp
#include "stdafx.h"
#include "TestStudent.h"
extern const int NUM;
extern Student allStudents[];
void print_student(){
for (int i = 0; i < NUM; ++i){
auto first_name = allStudents[i].first_name; //not working, why?
auto last_name = allStudents[i].last_name; //last_name is NULL?
std::cout << first_name << " " << last_name << std::endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
print_student();
return 0;
}
file: source.cpp
#include "stdafx.h"
#include "TestStudent.h"
const int NUM = 3;
static Student* get_all_students(){
Student* ss = new Student[NUM];
Student* ptr = ss;
for (int i = 0; i < NUM; ++i){
ptr->first_name = "test1";
ptr->last_name = "test2";
++ptr;
}
return ss;
}
Student* allStudents = get_all_students();
file: TestStudent.h
#pragma once
typedef struct _student{
const char* first_name;
const char* last_name;
} Student;
extern const int NUM;