2014-12-09 3 views
0

이 코드를 동적 배열로 사용하고 싶습니다. 불행히도, 나는 왜 프로그램이 할당 된 메모리를 사용하지 않는지 알 수 없다. AddToArray 함수의 매개 변수에 문제가 있습니까?동적 배열이 할당되었지만 사용할 수 없습니다.

이 코드를 직접 복사하여 IDE에 붙여 넣은 다음 컴파일하여 출력물을 볼 수도 있습니다. 메모리가 할당되었지만 사용되지 않은 것 같습니다. 명시 적 괄호없이 ++* 연산자를 통해 높은 우선 순위를 가지고있다, 때문에 코드에서

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

typedef struct { 
    float x; 
    float y; 
} DATA; 

int AddToArray (DATA item, 
       DATA **the_array, 
       int *num_elements, 
       int *num_allocated) 
{ 
    if(*num_elements == *num_allocated) 
    { // Are more refs required? 

    // Feel free to change the initial number of refs 
    // and the rate at which refs are allocated. 
    if (*num_allocated == 0) 
    { 
     *num_allocated = 3; // Start off with 3 refs 
    } 
    else 
    { 
     *num_allocated *= 2; 
    }// Double the number of refs allocated 

    // Make the reallocation transactional by using a temporary variable first 
    void *_tmp = realloc(*the_array, (*num_allocated * sizeof(DATA))); 

    // If the reallocation didn't go so well, inform the user and bail out 
    if (!_tmp) 
    { 
     printf("ERROR: Couldn't realloc memory!\n"); 
     return(-1); 
    } 
    // Things are looking good so far, so let's set the 
    *the_array = (DATA*)_tmp; 
    } 

    (*the_array)[*num_elements] = item; 
    *num_elements++; 

    return *num_elements; 
} 

int main() 
{ 
    DATA *the_array = NULL; 
    int num_elements = 0; // To keep track of the number of elements used 
    int num_allocated = 0; // This is essentially how large the array is 

    // Some data that we can play with 
    float numbers1[4] = {124.3,23423.4, 23.4, 5.3}; 
    float numbers2[4] = { 42, 33, 15, 74 }; 
    int i;  
    // Populate! 
    for (i = 0; i < 4; i++) 
    { 
    DATA temp; 
    temp.x = numbers1[i]; 
    temp.y = numbers2[i]; 
    if (AddToArray(temp, &the_array, &num_elements, &num_allocated) == -1) 
    return 1;    // we'll want to bail out of the program. 
    } 

    for (i = 0; i < 4; i++) 
    { 
    printf("(x:%f,y:%f)\n", the_array[i].x, the_array[i].y); 
    } 
    printf("\n%d allocated, %d used\n", num_allocated, num_elements); 
    // Deallocate! 
    free(the_array); 
    // All done. 
    return 0; 
} 
+0

왜 3 차 ref 또는 2 차 ref ...로 시작해야합니까? –

답변

3

, 당신은

*num_elements++;

(*num_elements)++;

을 변경해야 . 원하는 것은 주소에 저장하는 것입니다. 다른 방법은 아닙니다.

운영자 우선 순위 here을 확인하십시오.

+0

도움에 감사드립니다 :) –

+0

@ 프랑크 족을 가장 환영합니다. :-) –

1

기능

AddToArray() 
1

코드에서 버그가 포인터가 값을 증가되지 않는 것입니다에

(*num_elements)++; 

을 시도합니다.

.. 
    (*the_array)[*num_elements] = item; 
    (*num_elements)++; 
.. 

프로그래밍 할당입니까? 코드는 여기에서 많은 영역에서 개선 될 수 있습니다. 잘 작성되고 최적화 된 이런 종류의 문제에 대한 좋은 알고리즘이 많이 있습니다. 그 분야의 연구를 제안합니다.

관련 문제