c++ - 无法对包含字符串 C++ 的结构数组进行操作

标签 c++ arrays string struct structure

我有一个包含 string 字段的结构。我创建了一个包含这些结构的数组,然后我想将它们传递给一个函数(通过引用)。当我注释掉 string 字段时,一切正常,但如果我不这样做,程序就会崩溃。我在任何地方都找不到这个问题的答案..

这是代码(我将其缩减为仅显示问题):

struct student {
    int a;
    int b;
    string name[20];
    char status;
};

void operation(student the_arr[1],int number_of_students) {
    delete[] the_arr;
    the_arr = new student[3];
    for(int i = 0; i<3; i++) {
        the_arr[i].a = i+5;
        the_arr[i].b = i+4;
    }   
}

int main() {    
    student *abc;
    abc = new student[0];
    operation(abc, 0);  
    system("pause");
    return 0;
}

我需要数组是动态的,这样我就可以在需要时更改它的大小。

最佳答案

假设您不能使用 std::vector 而不是动态分配的数组,请遵循以下答案。在任何其他情况下,您应该使用标准库提供的容器。

注意:您的程序不会崩溃。编译器唯一会提示的是 allocating zero elements 部分,但会让您编译并运行该程序。

您的功能完全错误。使用动态分配时,您可以像这样简单地传递一个指针:

void operation(student* the_arr, int number_of_students) {

然后在你的函数中,你动态分配存储在 the_arr 指针中的内存,它不是通过引用传递的,因此导致创建一个局部指针变量,该变量在执行后将丢失指针:

void operation(student*& the_arr [...]

不过,我建议您避免使用以下解决方案,而是返回新指针:

student* operation(student* the_arr, int number_of_students) {
    delete[] the_arr;
    the_arr = new student[3];
    [...] 
    return the_arr; // <----
}

分配 abc = new student[0]; 没有任何意义。您正在尝试分配一个包含 0 个元素的数组。也许你的意思是 abc = new student[1];

关于c++ - 无法对包含字符串 C++ 的结构数组进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15575333/

相关文章:

c# - 获取输入字符串的位置然后在两端获取子字符串

c - printfs 系列中的第一个 printf() 发生故障,返回不可预测的结果

c++ - libshout 构建对 SSL_is_init_finished 的 undefined reference

c++ - 当调用函数修改指针时如何释放内存?

c++初学者---使用指针修改字符串

arrays - 如何遍历 Perl 中对哈希数组的引用?

python - 打印包含字符串和 2 个其他变量的变量

c++ - 当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数?

c++ - 在 OpenGL 中将深度渲染到纹理时出现奇怪的结果

php - mysql where 表中两个字段之间的数组