typedef'ed 포인터에 대한 포인터의 간단한 동적 배열을 구현해야합니다.
사용자가 요청할 때마다 realloc을 사용하면 배열 크기가 sizeof (pointer)만큼 증가합니다.
는 그래서 내가 가진 것은 이것이다 :realloc을 호출 한 후 메모리를 초기화 (0으로 설정)해야합니까?
Done reallocating
0 (nil)
1 (nil)
2 (nil)
3 0x20fe1
4 (nil)
5 (nil)
6 (nil)
7 (nil)
8 (nil)
9 (nil)
10 (nil)
11 (nil)
12 (nil)
13 (nil)
14 (nil)
15 (nil)
16 (nil)
17 (nil)
18 (nil)
19 (nil)
내가 3 요소에 대한 걱정, 그 내용 :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void* node;
void printmem(node* a, int c) {
int i;
for (i = 0; i < c; ++i)
{
printf("%d\t\t%p\n", i, a[i]);
}
}
int main(void) {
node* nodes = NULL;
int i = 0, count = 20;
for (i = 0; i < count; ++i)
{
nodes = realloc(nodes, sizeof(node));
}
printf("Done reallocating\n");
printmem(nodes, i);
// free(a);
return 0;
}
이 다음과 같은 출력을 제공합니다.
그래서 새로운 realloc 후에 메모리를 0으로 설정해야하는지 묻습니다.
편집 : C의 표준에 지적
그래서, H2CO3에 의해, realloc 함수에 새 호출은 다음과 같습니다 nodes[i] = NULL
: nodes = realloc(nodes, (i+1)*sizeof(node));
그리고 initiallization에 대한 그 후
, 내가 이런 짓을 그것은 또한 잘 작동했습니다.
Edit2가 :
지금이 있습니다
int main(void) {
node* nodes = NULL;
int i = 0, count = 20;
for (i = 0; i < count; ++i)
{
nodes = realloc(nodes, (i+1)*sizeof(node));
nodes[i] = NULL;
if (i == 1) {
nodes[i] = &count;
}
}
printf("Done reallocating\n");
printmem(nodes, i);
printf("\t*nodes[1] == %d\n", *(int*)nodes[1]);
printf("\tAddress of count is %p\n", &count);
// free(a);
return 0;
}
'realloc()'은 원래 버퍼에 있던 내용을 복사합니다. 새로운 블록이 원래 블록보다 크다면, 최종 블록의 요소 (즉, 원래의 배열에 존재하지 않는 요소)는 초기화되지 않을 것이다. –
@ H2CO3 : 새 블록은 이전보다 큽니다. 따라서 이전의 모든 데이터가 손실됩니까? – Chris
Naw. 한 번 더 내 의견을 읽으십시오. 초과 요소는 초기화되지 않고 메모리 블록의 시작 부분에있는 원본 내용이 보존됩니다. –