c 语言 malloc 示例
时间: 2023-06-22 17:35:39 浏览: 33
好的,下面是一个简单的 C 语言 malloc 示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!");
exit(0);
}
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
printf("Elements in array are: ");
for (i = 0; i < n; i++) {
printf("%d ", *(ptr + i));
}
free(ptr); // Freeing the allocated memory
return 0;
}
```
这个程序首先要求用户输入元素数量,然后使用 malloc 函数动态分配内存以存储这些元素。如果内存分配失败,程序将输出错误消息并退出。如果内存分配成功,则程序将要求用户输入每个元素的值,并将这些元素打印出来。最后,程序释放了动态分配的内存。