2013-04-22 3 views
0

사용자 입력에 의해 가변 크기로 배열을 선언하려고합니다.가변 배열 크기 (C)

은 지금까지 나는 이런 일이 :

typedef struct _object{ 
    int rowsAmount; 
    int columsAmount; 
    int* rows; 
    int* colums; 
} object; 

object* newObject(int ra, int ca){ 
    object* o = malloc(sizeof(object)); 
    o->rowsAmount = ra; 
    o->columsAmount = ca; 
    o->rows = [ra];  
    o->colums = [ca]; 
    return o; 
} 

int main(){ 
    newObject(3,4); 
} 

나는이 작동하지 않을 예상을하지만, 나는 이런 식으로 뭔가를 원하고, 나는 그것을하는 방법을 모르겠어요.

+0

2x 1d 어레이의 2d 어레이를 원하십니까? –

+1

컴파일도합니까? 기도하는 것은 무엇입니까?'m-> rows = [ra];'? – StoryTeller

+0

@LefterisE 나는 방금 C를 배우려고하는데, 이것은 크기 설정에 관한 것입니다. 방금 2 개의 어레이로 시도해 보았습니다. – Yananas

답변

0

동적 C에서는 데이터의 2 차원 배열을 할당 :

  • 전체 데이터 메모리를 할당. 그 기억은 arrayData에 의해 지적됩니다.
  • 각 행을

코드를 해당 메모리 주소로 각 행

  • 포인트에 대한 그 포인터를 포인터 하나의 1D 배열을 할당 :

    int *arrayData = malloc(sizeof(int) * rows * columns); 
    int **array = malloc(sizeof(int*) * rows); 
    for(int i=0; i < rows;++i){ 
        array[i] = arrayData + i * columns; 
    } 
    

    는 이제 array[row][col]으로 메모리에 액세스 할 수 있습니다.

  • +0

    니스, 고마워. – Yananas

    3

    기본적으로 여기에 동적 Matrix 객체가 구현되어있는 것처럼 보입니다. 또한 유사 freeoo->matrix에 할당 된 모든 메모리를이야 소멸자 기능 destroyObject을 만들어야합니다

    typedef struct _object{ 
        int rowsAmount; 
        int columsAmount; 
        int* matrix; 
        int** rows; 
    } object; 
    
    object* newObject(int ra, int ca){ 
        object* o = malloc(sizeof(object)); 
        o->rowsAmount = ra; 
        o->columsAmount = ca; 
        o->matrix = malloc(ra * ca * sizeof(int)); 
        o->rows = malloc(ra * sizeof(int*)); 
        for (size_t i = 0; i != ra; ++i) o->rows[i] = o->matrix + (i * ca); 
        return o; 
    } 
    

    : 당신은 같은 것을 원한다.

    편집 :

    그러나, 귀하의 코멘트 :

    는 "난 그냥 C를 배우려고 노력하고있어, 이것은 설정 크기에 대한 아니라 난 그냥 일어난. 2 개의 배열로 시도하십시오 "

    ...이 질문은 다소 혼란 스럽습니다. 여기에 "행"/ "열"용어를 사용 했음에도 불구하고 행렬을 2D 배열로 만들었지 만 C에서 배열을 동적으로 할당하는 방법을 이해하기 만하면됩니다.

    그런 경우 C의 배열은

    size_t array_size = 10; /* can be provided by user input */ 
    int* array = malloc(sizeof(int) * array_size); 
    

    그리고 당신이 작업을 완료되면 후, 동적으로 할당 된 배열을 해제해야합니다 :

    free(array); 
    
    +0

    감사합니다. – Yananas

    +0

    감사합니다. 나중에 물건을 이해할 때 이것을 매트릭스와 같은 것으로 만들 예정이므로 실제로 도움이되었습니다. – Yananas

    -1

    가장 쉬운 방법은 부스트를 사용하는 것입니다 동적으로 포인터 변수와 malloc을 사용하여 할당 : : multi_array 뿐만 아니라 임의의 수의 치수를 얻을 수 있습니까? n 차원 배열이 아닌 하나의 인접한 메모리 블록으로 매우 효율적으로 저장됩니다.

    CPU는 배열을 빠르게 탐색하도록 설계되었으므로 잠재적으로 이것을 사용하여 컴파일러의 캐싱/프리 페치/파이프 라이닝 기능을 활용할 수 있습니다.

    예는

    // 2 dimensions 
    int xDim; 
    int yDim; 
    cin >> xDim; // From user.. 
    cin >> yDim; 
    // Initialise array 
    boost::multi_array<int,2> my2dgrid(boost::extents[xDim][yDim]); 
    // Iterate through rows/colums 
    for(int j = 0 ; j < yDim-1; j++) { // Row traversal 
    for(int i = 0 ; i < xDim-1; i++) { // Column traversal 
        int value = grid[j][i]; // Get a value 
        grid[j][i] = 123; // set a value 
        // Do something... 
    } 
    
    +0

    OP가 C++을 지정하지 않았 음 –

    +0

    흠, 요점 : 나는 그 비트를 보지 못했습니다! – Ronnie

    0

    넌 구조 밖으로 사용자로부터 입력 크기와 배열을 생성 할 수있다. 당신이 정말로 구조 배열을 필요로하는 경우

    int *array1; 
    int size; 
    // get input from user 
    array1 = malloc(sizeof(int)*size); 
    // do your stuff 
    free(array1); 
    

    는 2 차원 배열을 원하는 경우

    ,

    int **array2; 
    int row, col; 
    int i; 
    array2 = malloc(sizeof(int*)*row); 
    for(i=0;i<row;++i) 
        array2[i] = malloc(sizeof(int)*col); 
    //use the array 
    for(i=0;i<row;++i) 
        free(array2[i]); 
    free(array2); 
    

    , 다음

    typedef struct _object{ 
        int rowsAmount; 
        int columsAmount; 
        int** array; 
        //int* colums; 
    } object; 
    
    object* newObject(int ra, int ca){ 
        int i; 
        object* o = malloc(sizeof(object)); 
        o->rowsAmount = ra; 
        o->columsAmount = ca; 
        o->array = malloc(sizeof(int*)*ra);  
        for(i=0;i<ra;i++) 
         o-<array[i]=malloc(sizeof(int)*ca); 
        return o; 
    } 
    
    int main(){ 
        newObject(3,4); 
    } 
    
    -1
    #include <stdio.h> 
    #include <stdlib.h> 
    
    typedef struct _object{ 
        int rowsAmount; 
        int columsAmount; 
        int **rows; 
    // int* colums; 
    } object; 
    
    object* newObject(int ra, int ca){ 
        int r; 
        object* o = malloc(sizeof(object)); 
        o->rowsAmount = ra; 
        o->columsAmount = ca; 
        o->rows = (int **)malloc(ra*sizeof(int *)); 
        for(r=0;r<ra;++r) 
         o->rows[r] = (int*)malloc(ca*sizeof(int)); 
        return o; 
    } 
    
    int main(){ 
        object *obj= newObject(3,4); 
        obj->rows[2][3]=5; 
        return 0; 
    } 
    
    +0

    downvote 이유는 무엇입니까? – BLUEPIXY

    0

    내가 생각하는 당신의 newObject() 기능에 대한 메모리를 할당 범위 변수를 대신 사용할 수있는 경우 사람들은 동적 메모리 할당을 사용합니다. 예를 들어, 배열을 사용하지 않고 사용자의 입력이 스택에 할당 할 수 있습니다에서 크기의 malloc/무료 :

    물론
    int array_size; 
    scanf("%d", &array_size); 
    if (array_size > 0) { 
        /* Allocate array on stack */ 
        float array[array_size]; 
    
        /* ... do smth with array ... */ 
    } 
    /* Out of scope, no need to free array */ 
    

    데이터 블록이 큰 경우는, 힙 메모리가 필수이지만, 작은 할당에 대한 범위가 잘됩니다.