简体   繁体   中英

Assigning string to char array vs. struct function

Okay so I know that the following doesn't work. I can't declare a char array, and then assign it later as follows.

char a[20]; 
a = "Hello World"; //SYNTAX ERROR

cout << a; 

However, when I use a struct data type, it seems like I can assign a char array after it's been initialized.

#include <iostream>
using namespace std;

struct Student 
{
    char name[10]; 
}

int main()
{
   Student student1; 
   student1 = {"Will"};

   cout << student1.name; 
}

This prints out: Will

Why does this work?

The 2nd code works because a temporary is being initialized by Aggregate Initialization , and then that temporary is assigned to student1 , which copies each member's value.

A simple struct like you have has aggregate initialization and is trivially copyable. So when you write

student1 = {"Will"};

a temporary object Student is created via aggregate initialization and then the copy assignment operator is called.

But what you should be using is std::string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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