2010-05-12 7 views
0

gcc 4.4.3 c89선언 후 배열 초기화

다음 코드는 내가 수행하려고 시도하는 샘플입니다. 함수에 들어가기 전까지는 배열의 실제 크기를 알 수 없습니다. 그러나, 선언 한 후에 배열 크기를 설정할 수 있다고 생각하지 않습니다. 다른 함수가 장치 이름에 액세스해야하므로 전역으로 필요합니다. 어떤 제안에 대한

많은 감사,

/* global */ 
char *devices_names[]; 

void fill_devices(size_t num_devices) 
{ 
    devices_names[num_devices]; 

    /* start filling */ 
} 

답변

2

당신은 동적으로 malloc을 사용하여 메모리를 할당해야합니다 :

char **device_names; 

void fill_devices(size_t num_devices) 
{ 
    device_names = malloc(num_devices * sizeof(char*)); 
} 

을 그리고 당신이 더 이상 필요하지 않을 때 메모리를 무료로 free(device_names);를 사용 .

+0

사과, sepp2k. 우연히 내 대답 대신 실수로 편집했습니다. –

3

는 동적 확인 :

char **g_device_names; 
int g_num_devices; 

void fill_devices(size_t num_devices) { 
    g_device_names = malloc(sizeof(char*) * num_devices); 
    g_num_devices = num_devices; 
    ... 
} 
2

당신은 포인터를 사용한다, 그래서 당신은 배열이 아직 선언되지 않은 방법을 입력 할 때. malloc을 사용하여 올바른 크기를 설정할 수 있습니다. 이 기사를보십시오 : arrays and malloc

3

전역 배열을 사용하는 경우 선언 할 때 크기 (또는 최대 크기)를 알아야합니다. 예 :

char *devices_names[MAX_DEVICES]; 

이렇게 할 수 없다면 포인터와 동적으로 할당 된 메모리를 사용할 수밖에 없습니다.

예.

char **devices_names = 0; 

void fill_devices(size_t num_devices) 
{ 
    devices_names = malloc(num_devices * sizeof *devices_names); 

    /* ... */ 
} 

물론 이것은 할당되기 전에 사람이 배열에 액세스하는 것을 방지하고 언제 자유롭게합니까?