简体   繁体   English

在C ++中将字符串指针传递给结构

[英]Passing a string pointer to a struct in C++

I'm trying to pass various string s into members of a Struct via pointer but I am doing something fundamentally incorrect. 我试图通过pointer将各种string传递给Struct成员,但是我所做的事情根本上是不正确的。 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 . 以下过程适用于其他类型的数据,例如intchar 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 : 尝试编译以下算法来初始化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*, ..

You're actually defining, for example, an array of 15 strings in the location field. 例如,您实际上是在location字段中定义一个由15个字符串组成的数组。 Either use regular strings; 使用常规字符串; eg: 例如:

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

or use char arrays: 或使用char数组:

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;

When you declare char a[10] , you're creating an array of 10 characters. 声明char a[10] ,将创建一个10个字符的数组。 When you declare an std::string , you're creating a string that can grow to arbitrary size. 声明std::string ,您正在创建一个可以增长为任意大小的字符串。 When you declare an std::string[15] , you're creating an array of 15 strings that can grow to arbitrary size. 声明std::string[15] ,您正在创建一个由15个字符串组成的数组,该数组可以增长为任意大小。

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;

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. string location[15]表示您想创建一个string 15个实例,并且每个单独的实例可以具有任意长度的文本。

Instead of d->location , you need to assign one of those 15 strings: d->location[0] = location , d->location[1] = location , etc. 代替d->location ,您需要分配这15个字符串之一: d->location[0] = locationd->location[1] = location等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM