Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to pass string array in function and assign to a variable?

Tags:

c++

arrays

I got this error while coding a simple function. This is my function specification.

string studentName;
string courseTaken[3];
void setStudent(string, string[]); 

void Student::setStudent(string n, string a[])
{
   studentName= n;
   courseTaken = a;
}

This is the error I have gotten:

incompatible types in assignment of string* to string [3] on this line courseTaken = a;

In my code, I never declared any pointer or char.

I don't quite understand what is going wrong here.

like image 895
Einn Hann Avatar asked Jan 29 '26 23:01

Einn Hann


1 Answers

You can not assign array of strings string a[] to array courseTaken using = operator. The expression string a[] is equivalent to std::string*. That is why you get the compiler error.

This may be what you wanted:

#include <iostream>
using namespace std;

class Student
{
    public:
        string studentName;
        string courseTaken[3];
        void setStudent(string n, string a[]); 
};

void setStudent(string n, string a[]); 

void Student::setStudent(string n, string a[])
{
   studentName = n;
   for(int i=0; i < sizeof(courseTaken)/sizeof(courseTaken[0]); i++)
    courseTaken[i] = a[i];
}

int main()
{
    Student student;

    string courses[3] = {"Cobol","C++","Fortran"};
    student.setStudent("Eva", courses);

    for (int i = 0; i < 3; i++){
        cout << student.courseTaken[i] << endl;
    }

    return 0;
}

Output:

Cobol                                                                                                                                        
C++                                                                                                                                          
Fortran 
like image 69
sg7 Avatar answered Jan 31 '26 12:01

sg7