안녕하세요.이 상황에 처했습니다. malloc을 사용하여 10 개의 포인터 배열을 제공하고 있습니다. gdb에서 테스트 포인터를 볼 때 그 중 하나 (세 번째)는 0x0을 가리 킵니다. 때로는 apple [2] -> string = "hello"를 사용할 때 코드가 segfault됩니다. 왜 malloc이 이것을합니까? 도움에 미리 감사드립니다.null 포인터를 초기화하는 Malloc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void)
{
typedef struct test
{
char *string;
int data;
} test;
test *apple[10]; // Declare an array of 10 test pointers. This line results in one of the pointers having a null value.
apple[0] = malloc(sizeof(test));
apple[0]->string = "hello";
printf("The string is %s\n",apple[0]->string);
printf("Size of apple[0]->data is %d\n",sizeof(apple[0]->data));
printf("Size of tester is %d\n",sizeof(test));
free(apple[0]);
return 0;
}
포인터 배열이 어떻게 작동하는지 알고 싶었습니다. 나는 10 개의 모든 포인터를 사용하려고하지는 않았다. 그래서 내가 필요한 것을 malloc 할 필요가 있습니까? 우연의 일치입니까, 세 번째 포인터는 0x0입니까?
예, 초기화되지 않은 : 당신이
apple[0]
, 또는의 malloc() 전체 배열처럼 (지금은 정말 필요하지 않습니다 포인터) 접근 방식, 당신은() (의 malloc에 자신의 모든 요소가 메모리는 모든 값을 가질 수 있습니다. 오직'malloc()'만 있으면되지만 쇼핑몰에 대해 알 수있는 방법이 필요합니다. 예를 들어'test * apple [10] = {0};'과 같이 unmalloc 된 모든 원소를'NULL '로 설정하십시오. – hmjd