English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C 언어에서 void 포인터는 객체 포인터 타입으로 묵시적 변환됩니다. 이 함수malloc()
C89표준에서 void를 반환합니다 *C의 초기 버전에서는malloc()
char을 반환합니다 *C에서 ++언어에서 기본적으로malloc()
int 값을 반환합니다. 따라서 포인터를 객체 포인터로 변환하는 명시적 변환을 사용합니다.
아래는 C 언어로 메모리를 할당하는 문법입니다.
pointer_name = malloc(size);
여기서는
pointer_name-포인터의 이름을 주세요.
크기-바이트为单位로 할당된 메모리 크기입니다.
아래는malloc()
C 언어 예제.
#include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = malloc(n * sizeof(int)); printf("\nError! memory not allocated."); exit(0); } printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); } printf("\nSum : %d", s); return 0; }
출력 결과
배열 요소를 입력하세요 : 2 28 12 32 Sum : 74
위의 C 언어 예제에서 명시적 강제 변환을 수행하면 오류가 표시되지 않습니다.
아래는 C ++언어가 메모리를 할당하는 문법.
pointer_name = (cast-타입*) malloc(size);
여기서는
pointer_name-포인터의 이름을 주세요.
cast- 타입-할당된 메모리 데이터 타입을 강제 변환하려면malloc()
.
크기-바이트为单位로 할당된 메모리 크기입니다.
아래는malloc()
C ++언어 예제.
#include <iostream> using namespace std; int main() { int n = 4, i, *p, s = 0; p = (int *)malloc(n * sizeof(int)); cout << Error! memory not allocated. exit(0); } cout << Enter elements of array : for(i = 0; i < n; ++i) { cin >> (p + i); s += *(p + i); } cout << Sum : ", s; return 0; }
출력 결과
배열 요소를 입력하세요 : 28 65 3 8 Sum : 104
위의 C ++언어 예제에서, 명시적 변환을 수행하지 않으면 프로그램이 다음과 같은 오류를 표시합니다.
error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive] p = malloc(n * sizeof(int));