2011-09-12 5 views
0

포인터를 함수에 전달하는 중 호출 된 함수의 구조체 배열을 초기화하고 해당 배열 main 함수를 사용하려고합니다. 그러나 나는 그것을 주요 기능에서 얻을 수 없었다.초기화 된 배열 배열을 가져올 수 없습니다.

typedef struct _testStruct 
{ 
    int a; 
    int b; 
} testStruct; 

void allocate(testStruct** t) 
{ 
    int nCount = 0; 
    int i = 0; 
    printf("allocate 1\n"); 
    t = (testStruct**)malloc(10 * sizeof(testStruct)); 
    for(i = 0; i < 10; i++) 
    { 
     t[i] = (testStruct *) malloc(10 * sizeof(testStruct)); 
    } 
    for(nCount = 0 ; nCount < 10; nCount++) 
    { 
     t[nCount]->a = nCount; 
     t[nCount]->b = nCount + 1; 

     printf("A === %d\n", t[nCount]->a); 
    } 

} 
int main() 
{ 
    int nCount = 0; 
    testStruct * test = NULL; 
    int n = 0; 
    allocate(&test); 
    for(nCount = 0 ; nCount < 10; nCount++) 
    { 
     if (test == NULL) 
     { 
      printf("Not Allocated\n"); 
      exit(0); 
     } 
     //printf("a = %d\n",test[nCount]->a); 
     /*printf("a = %d\n",test->a); 
     printf("b = %d\n",test->b); */ 
    } 

    return 0; 
} 

내가이 필요로 작동하는 이중 포인터를 전달해야 할주의 사항 : 다음은 내 코드입니다. 도움 주셔서 감사합니다.

+0

질문이 있으십니까? –

+0

이것은 무관 ​​한 코드 조각이 무작위로 재연 된 것처럼 보입니다. 'main' 함수에서 배열은 분명히 1D입니다. 그러나'allocate '내부의 코드는 분명히 2D 배열을 할당하려는 시도로부터 복사됩니다. 그럼, 당신이 할당하려고하는 것은 무엇입니까? 1D 배열? 또는 2D 배열? 먼저 결정해야합니다. – AnT

답변

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

typedef struct _testStruct 
{ 
    int a; 
    int b; 
} testStruct; 

void allocate(testStruct** t) 
{ 
    int nCount = 0; 
    printf("allocate 1\n"); 
    testStruct *newT = (testStruct*)malloc(10 * sizeof(testStruct)); 
    for(nCount = 0 ; nCount < 10; nCount++) 
    { 
     newT[nCount].a = nCount; 
     newT[nCount].b = nCount + 1; 

     printf("A === %d\n", newT[nCount].a); 
    } 

    *t = newT; 

} 
int main() 
{ 
    int nCount = 0; 
    testStruct * test = NULL; 
    allocate(&test); 
    for(nCount = 0 ; nCount < 10; nCount++) 
    { 
     printf("a = %d\n",test[nCount].a); 
     printf("a = %d\n",test[nCount].b); 

    } 

    return 0; 
} 

작동해야합니다.

+0

감사합니다 Carl, 작동 중입니다 :) – user940959

+0

감사합니다 에드 힐, U 저의 밤 저장하기 :) – user940959

0
t = (testStruct**)malloc(10 * sizeof(testStruct)); 

t하지 test에 할당된다. 아마도 원하는지

*t = (testStruct*)malloc(10 * sizeof(testStruct)); 

대신에? 나는 잘 모르겠다. 나는 많은 포인터가있을 때 길을 잃는 경향이있다. 어쨌든 함수에 전달하는 포인터에 아무 것도 지정하지 않는 것 같습니다.

0

구조 배열을 만들고 싶지만 allocate 함수는 2 차원 배열처럼 데이터 구조를 만듭니다. 또한, 구조를 호출자에게 다시 돌려주지 않는 것이 좋습니다. 나는 당신이 포인터에 대해 혼란스러워했다고 생각합니다. malloc() 그리고 당신이하고있는 모든 간접 참조. 수정 된 프로그램에 대한 @Ed Heal의 대답을 확인하십시오.