| |

VerySource

 Forgot password?
 Register
Search
View: 655|Reply: 5

A question about the assignment of struct character array elements

[Copy link]

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-2-11 12:00:02
| Show all posts |Read mode
Someone asked me a question, the code is as follows
#include <iostream>
using namespace std;

struct pizza
{
char company [3];
double diameter;
double weight;
};

int main ()
{
pizza * ps = new pizza [3];
ps [0] .company = "qq";
ps [0] .diameter = 1.2;
ps [0] .weight = 1.2;
      
ps [1] .company = "w";
ps [1] .diameter = 2.2;
ps [1] .weight = 2.2;

ps [2] .company = "e";
ps [2] .diameter = 3.2;
ps [2] .weight = 3.2;

cout << ps [0] .company << endl;
cout << ps [0] .diameter << endl;
cout << ps [0] .weight << endl;

cout << ps [1] .company << endl;
cout << ps [1] .diameter << endl;
cout << ps [1] .weight << endl;

cout << ps [2] .company << endl;
cout << ps [2] .diameter << endl;
cout << ps [2] .weight << endl;

delete [] ps;

cin.get ();
cin.get ();
return 0;
}
The above error should be a problem with character array constants (I use java more, c ++ is still a bit of the impression I used to see), ps [0] .company = "qq"; This definitely does not work for string constants. I changed char company [3]; in the structure to char * company;
My question is, how to not change the definition of the structure, that is, also use char company [3] ;, modify the assignment statement, and assign by pointer? (Not sure how to get a pointer to the company element)
What a mess, prawns understand?
Reply

Use magic Report

0

Threads

55

Posts

44.00

Credits

Newbie

Rank: 1

Credits
44.00

 Invalid IP Address

Post time: 2020-4-6 19:00:01
| Show all posts
Use string instead of char * / char []
Reply

Use magic Report

0

Threads

63

Posts

43.00

Credits

Newbie

Rank: 1

Credits
43.00

 China

Post time: 2020-4-7 12:15:01
| Show all posts
Use strcpy instead of =, pay attention to the size of the array
Reply

Use magic Report

0

Threads

63

Posts

43.00

Credits

Newbie

Rank: 1

Credits
43.00

 China

Post time: 2020-4-7 13:00:01
| Show all posts
such as: strcpy (ps [0] .company, "qq");
Reply

Use magic Report

0

Threads

63

Posts

43.00

Credits

Newbie

Rank: 1

Credits
43.00

 China

Post time: 2020-4-7 15:00:02
| Show all posts
Add #include <cstring>
Reply

Use magic Report

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

 Author| Post time: 2020-4-15 09:15:01
| Show all posts
Thank you!
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list