developer tip

C에서 구조체 배열을 어떻게 만드나요?

copycodes 2020. 9. 12. 10:12
반응형

C에서 구조체 배열을 어떻게 만드나요?


각 구조체가 천체를 나타내는 구조체 배열을 만들려고합니다.

나는 구조체에 대한 경험이 많지 않기 때문에 전체 배열 대신에 구조체를 사용하기로 결정했습니다. 그러나 나는 계속해서 수많은 다른 오류가 발생합니다. 다양한 스레드와 StackOverflow (예 : CC의 구조체 배열-구조체 배열 초기화) 에서 본 기술을 구현하려고 시도했지만 모두 적용 할 수있는 것은 아닙니다.

이 글을 읽어보신 분들을위한 추가 정보 : 저는이 중 어떤 것도 동적 일 필요는 없습니다. 모든 것의 크기를 미리 알고 / 정의합니다. 또한 인수를 정의한 여러 다른 메서드 (예 : GLUT 메서드)에서이 항목에 액세스하므로 전역 배열이되어야합니다.

이것은 헤더에서 구조체를 정의하는 방법입니다.

struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
};

구조체의 내부를 정의하기 전에 정의하고있는 다른 전역 변수 목록이 있는데 그 중 하나는이 구조체의 배열입니다 (기본적으로 내 말이 너무 불분명하다면 아래 줄 위 항목 위에 있음) :

struct body bodies[n];

아시다시피, n제가 합법적으로 정의한 것입니다 (예 :) #define n 1.

이 배열을 여러 가지 방법으로 사용하지만 가장 쉽고 공간을 적게 차지하는 배열은 메인의 단순화 된 형태입니다. 여기에서는 각 구조체의 모든 변수를 초기화하여 어떤 식 으로든 수정하기 전에 변수를 확실하게 설정합니다.

  int a, b;
 for(a = 0; a < n; a++)
 {
        for(b = 0; b < 3; b++)
        {
            bodies[a].p[b] = 0;
            bodies[a].v[b] = 0;
            bodies[a].a[b] = 0;
        }
        bodies[a].mass = 0;
        bodies[a].radius = 1.0;
 }

내가 직면 한 현재 오류는 nbody.c:32:13: error: array type has incomplete element type32 줄이 구조체 배열을 만드는 곳입니다.

마지막 설명은 헤더로 위의 공간을 의미 int main(void)하지만 동일한 *.c파일에 있습니다.


#include<stdio.h>
#define n 3
struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
};

struct body bodies[n];

int main()
{
    int a, b;
     for(a = 0; a < n; a++)
     {
            for(b = 0; b < 3; b++)
            {
                bodies[a].p[b] = 0;
                bodies[a].v[b] = 0;
                bodies[a].a[b] = 0;
            }
            bodies[a].mass = 0;
            bodies[a].radius = 1.0;
     }

    return 0;
}

이것은 잘 작동합니다. 그런데 질문이 명확하지 않았으므로 소스 코드의 레이아웃을 위와 일치 시키십시오.


나는 당신도 그렇게 쓸 수 있다고 생각합니다. 나는 또한 학생이기 때문에 당신의 어려움을 이해합니다. 조금 늦은 응답이지만 괜찮습니다.

#include<stdio.h>
#define n 3

struct {
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}bodies[n];

따라서 다음을 사용하여 모두 정리하십시오 malloc().

int main(int argc, char** argv) {
    typedef struct{
        char* firstName;
        char* lastName;
        int day;
        int month;
        int year;

    }STUDENT;

    int numStudents=3;
    int x;
    STUDENT* students = malloc(numStudents * sizeof *students);
    for (x = 0; x < numStudents; x++){
        students[x].firstName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].firstName);
        students[x].lastName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].lastName);
        scanf("%d",&students[x].day);
        scanf("%d",&students[x].month);
        scanf("%d",&students[x].year);
    }

    for (x = 0; x < numStudents; x++)
        printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

    return (EXIT_SUCCESS);
}

움직임

struct body bodies[n];

이후에

struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
};

나머지는 모두 괜찮아 보입니다.


Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.


That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file. Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.


Solution using pointers:

#include<stdio.h>
#include<stdlib.h>
#define n 3
struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double *mass;
};


int main()
{
    struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
    int a, b;
     for(a = 0; a < n; a++)
     {
            for(b = 0; b < 3; b++)
            {
                bodies[a].p[b] = 0;
                bodies[a].v[b] = 0;
                bodies[a].a[b] = 0;
            }
            bodies[a].mass = 0;
            bodies[a].radius = 1.0;
     }

    return 0;
}

참고URL : https://stackoverflow.com/questions/10468128/how-do-you-make-an-array-of-structs-in-c

반응형