Passing a string pointer to a struct in C++

2019-08-31 01:17发布

问题:

I'm trying to pass various strings into members of a Struct via pointer but I am doing something fundamentally incorrect. What I think is that it doesn't need to be dereferenced. The process below works for other types of data such as int or char. For example:

typedef struct Course {
    string location[15];
    string course[20];
    string title[40];
    string prof[40];
    string focus[10];
    int credit;
    int CRN;
    int section;
} Course;


void c_SetLocation(Course *d, string location){
    d->location = location;
    . . .
}

I get an error when I try to compile the following algorithm to initialize a Course:

    void c_Init(Course *d, string &location, ... ){
        c_SetLocation(d, location[]);
        . . .

    }

The error:

error: cannot convert ‘const char*’ to ‘std::string* {aka std::basic_string<char>*}’ for argument ‘2’ to ‘void c_Init(Course*, std::string*, ..

回答1:

You're actually defining, for example, an array of 15 strings in the location field. Either use regular strings; e. g.:

typedef struct Course {
    string location;
    string course;
    string title;
    string prof;
    string focus;
    int credit;
    int CRN;
    int section;
} Course;

or use char arrays:

typedef struct Course {
    char location[15];
    char course[20];
    char title[40];
    char prof[40];
    char focus[10];
    int credit;
    int CRN;
    int section;
} Course;


回答2:

When you declare char a[10], you're creating an array of 10 characters. When you declare an std::string, you're creating a string that can grow to arbitrary size. When you declare an std::string[15], you're creating an array of 15 strings that can grow to arbitrary size.

Here's what your struct should look like:

typedef struct Course {
    std::string location;
    std::string course;
    std::string title;
    std::string prof;
    std::string focus;
    int credit;
    int CRN;
    int section;
} Course;


回答3:

string location[15] means that you want to create 15 instances of a string, and each of those individual instances can have any length of text.

Instead of d->location, you need to assign one of those 15 strings: d->location[0] = location, d->location[1] = location, etc.