2017-10-07 6 views
0

매스 센터 프로그램을 만들고 일반화하려고하는데, 3D로만 작동합니다. 3D 및 질량 요소가있는 구조 사용. 유형 객체의 변수 수는 사용자가 정의하고 싶습니다. 나 아닙니다. 하지만 루프를 사용하여 변수를 만드는 방법을 찾을 수 없습니다. 어쩌면 다른 방법이있을 수 있습니다. 단지 그것에 대해 알지 못합니다. 다음은 내 코드의 예입니다. 전체 코드는 아니지만 모든 방정식에 대해 동일한 논리입니다.for-loop를 사용하여 초기화되는 C 구조체

#include <stdio.h> 
#include <stdlib.h> 

struct objects 
{ 
    int Xcdnt; 
    int Ycdnt; 
    int Zcdnt; 
    int Mass; 
}; 

int main() 
{ 

    int objectcount = 0; 
    int dimensioncount = 0; 

    printf("How many objects are there?"); 
    scanf(" %d", &objectcount); 

    printf("How many dimensions are used?"); 
    scanf(" %d", &dimensioncount); 

    for(int i = 0; i < objectcount; i++) 
    { 
     struct objects (i); 
    } 

    for(int i = 0; i < objectcount; i++) 
    { 
     printf("X coordinate is %d.\n", (i).Xcdnt); 
    } 

    return 0; 

} 

답변

0

개체의 배열을 malloc해야합니다. 현재 코드는, foo 배열의 이름입니다

struct objects foo[objectcount]; 

을 만드는 대신 루프에, 당신이 쓰는 것 객체의 배열을 만들려면 같은 일

struct objects* objects = malloc(objectcount * sizeof(struct objects)); 
for(int i = 0; i < objectcount; i++) 
{ 
    objects[i].Xcdnt = 42; 
    ..... 

} 
0

을 파괴 looops하고, objectcount은 배열에있는 항목 수입니다.

다음 각 요소에 액세스하는 코드는 다음과 같습니다

for(int i = 0; i < objectcount; i++) 
{ 
    printf("X coordinate is %d.\n", foo[i].Xcdnt); 
} 

당신이 실제로 그것을 인쇄하기 전에 foo[i].Xcdnt에 값을 할당하기 위해 그 전에 다른 단계가 필요하지만.

0

사용 malloc에 ​​동적으로

struct objects* objs = malloc(sizeof *objs * objectcount); 

당신은이 같은 지역의 배열을 만들 수있는 배열을 만들려면 :

struct objects objs[objectcount]; 

하지만 너무 큰 있다면 당신은 스택을 폭파 위험이 있습니다.

1

이것은 C에서 메모리를 다루는 기본적인 부분입니다. 전구를 윙크하기 전에 친구가되어야하는 것은 어렵지 않습니다. 당신은 동적 메모리, malloc, callocrealloc를 할당하는 세 가지 도구가

을 (참고 컴파일러는 C99 가변 길이 배열 객체를 지원 경우, 당신은 여기에 언급되지 않은, 동적으로 할당하는 대신 VLA를 사용할 수 있습니다) .(callocmalloc과 같은 일을하지만 제로로 모든 바이트를 초기화 - 유용한 모든 메모리가 초기화되고 약간 느린 malloc보다 보험에 가입 할 경우) 귀하의 예를 들어

, 당신이 당신의 개체를 동적으로 메모리를 할당 할 수있다 (에게 아래의 /* comments */에서 추가 정보)를 다음과 같이

#include <stdio.h> 
#include <stdlib.h> 

typedef struct { /* a typedef will do (and make things easier) */ 
    int xcdnt;  /* C generally uses all lowercase variable and */ 
    int ycdnt;  /* function names, avoiding MixedCase or  */ 
    int zcdnt;  /* camelCase, reserving all uppercase for  */ 
    int mass;  /* constants and macros.      */ 
} object; 

int main (void) { 

    int objectcount = 0; 
    int dimensioncount = 0; 
    object *objects = NULL; 

    printf ("How many objects are there?: "); 
    if (scanf (" %d", &objectcount) != 1) { /* validate ALL user input */ 
     fprintf (stderr, "error: invalid conversion or EOF.\n"); 
     return 1; 
    } 

    printf ("How many dimensions are used?: "); 
    if (scanf (" %d", &dimensioncount) != 1) { 
     fprintf (stderr, "error: invalid conversion or EOF.\n"); 
     return 1; 
    } 

    /* create objectcount objects using calloc */ 
    objects = calloc (objectcount, sizeof *objects); 

    if (!objects) { /* validate all memory allocations */ 
     fprintf (stderr, "error: virtual memory exhausted.\n"); 
     return 1; 
    } 

    /* create some random values */ 
    for (int i = 0; i < objectcount; i++) { 
     objects[i].xcdnt = i; 
     objects[i].ycdnt = i + 1; 
     objects[i].zcdnt = i + 2; 
     objects[i].mass = i % 10 + 5; 
    } 

    printf ("\ndimensioncount: %d\n\n", dimensioncount); 

    /* output the random data in objects */ 
    for (int i = 0; i < objectcount; i++) { 
     printf ("X coordinate is %d.\nY coordinate is %d.\n" 
       "Z coordinate is %d.\nmass is: %d\n\n", 
       objects[i].xcdnt, objects[i].ycdnt, objects[i].zcdnt, 
       objects[i].mass); 
    } 

    free (objects); /* don't forget to free the memory you allocate */ 

    return 0; 
} 

사용 예/출력을

$ /bin/dynamicobjects 
How many objects are there?: 10 
How many dimensions are used?: 3 

dimensioncount: 3 

X coordinate is 0. 
Y coordinate is 1. 
Z coordinate is 2. 
mass is: 5 

X coordinate is 1. 
Y coordinate is 2. 
Z coordinate is 3. 
mass is: 6 

<snip... objects[2-7]> 

X coordinate is 8. 
Y coordinate is 9. 
Z coordinate is 10. 
mass is: 13 

X coordinate is 9. 
Y coordinate is 10. 
Z coordinate is 11. 
mass is: 14 

메모리 사용/오류 동적으로 메모리를 할당하는 쓰기 코드에서 확인

, 당신은 할당 된 메모리의 블록에 대한 2 개 책임있다 : (1) 항상 시작 주소에 대한 포인터를 유지를 메모리 블록에 대해, (2) 더 이상 필요하지 않을 때 이 해제되어이 될 수 있습니다.

메모리 오류 검사 프로그램을 사용하면 할당 된 메모리 블록의 경계를 넘어 서기를 시도하거나 초기화되지 않은 값에 조건부 점프를 읽거나 시도하지 않도록 할 수 있습니다. , 할당 한 모든 메모리를 확보했는지 확인하십시오.

Linux의 경우 valgrind이 정상 선택입니다. 모든 플랫폼에 대해 유사한 메모리 검사기가 있습니다. 그들은 모두 사용하기 쉽고, 프로그램을 실행하면됩니다.

$ valgrind ./bin/dynamicobjects 
==9105== Memcheck, a memory error detector 
==9105== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. 
==9105== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info 
==9105== Command: ./bin/dynamicobjects 
==9105== 
How many objects are there?: 10 
How many dimensions are used?: 3 

dimensioncount: 3 

X coordinate is 0. 
Y coordinate is 1. 
Z coordinate is 2. 
mass is: 5 

<snip... remaining> 

==9105== 
==9105== HEAP SUMMARY: 
==9105==  in use at exit: 0 bytes in 0 blocks 
==9105== total heap usage: 1 allocs, 1 frees, 160 bytes allocated 
==9105== 
==9105== All heap blocks were freed -- no leaks are possible 
==9105== 
==9105== For counts of detected and suppressed errors, rerun with: -v 
==9105== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) 

할당 한 메모리를 모두 비우고 메모리 오류가 없는지 항상 확인하십시오.

궁금한 점이 있으면 자세히 살펴보고 알려주세요.