I have a problem using a struct
in the C language.
It is very strange !!!
I cant use course
struct in student
struct.
I have defined it before but ... why?
struct course
{
int no;
char name[30];
int credits;
float score;
};
struct student
{
int no;
char name[50];
course c[3];
};
My language is c not c++
One of the differences between C++ and C is that you can omit type keywords such as class
and struct
when using C++ types.
The problem is the line course c[3];
. In order to make it work, you have two choices--you can use a typedef on your struct course
:
typedef struct _course // added an _ here; or we could omit _course entirely.
{
int no;
char name[30];
int credits;
float score;
} course;
or you can add the keyword struct
in front of the broken line, ie struct
course c[3];
.
You need to prefix the struct name with the struct
keyword:
struct course
{
int no;
char name[30];
int credits;
float score;
};
struct student
{
int no;
char name[50];
struct course c[3];
};
struct course c[3];
应该管用...
struct student {
/* ... */
struct course c[3];
}
or
typedef struct _course {
/* ... */
} course;
struct student {
/* ... */
course c[3];
}
You should actually be able to define an anonymous struct and then typedef it, so:
typedef struct {
/* stuff */
} course;
and then as the others have said,
struct student {
course c[3];
}
typedefs are helpful, because they allow you to shorten declarations, so you are not always having to type the word struct
.
Here is an example involving typedef-ing your structs. It also includes a course struct in the student struct.
#include <stdio.h>
#include <string.h>
typedef struct course_s
{
int no;
char name[30];
int credits;
float score;
} course;
typedef struct student_s
{
int no;
char name[50];
course c[3];
} student;
bool isNonZero(const int x);
int main(int argc, char *argv[])
{
int rc = 0;
student my_student;
my_student.c[0].no = 1;
return rc;
}
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.