C-动态内存分配-malloc函数
在本教程中,我们将学习使用c编程语言动态分配内存的malloc函数。
malloc函数
我们使用malloc函数来分配指定大小的内存块。
该函数返回类型为" void"的指针,因此,我们可以将其分配给任何类型的指针变量。
如果无法分配所需的内存空间,则malloc函数将返回NULL。
Malloc语法
以下是malloc函数的语法。
ptr = (cast_type *) malloc (byte_size);
其中," ptr"是类型" cast_type"的指针变量," byte_size"是我们要分配的内存大小。
Malloc的例子
在下面的示例中,我们分配大小为5个字节的内存空间来存储5个字符。
//char pointer char *cptr; //allocate memory cptr = (char *) malloc (5 * sizeof(char));
我们可以在内存中表示如下。
我们首先计算byte_size,即(5 * sizeof(char))。
注意! sizeof(char)给我们1个字节,我们要保存5个字符,因此,所需的总存储空间为5x1 = 5个字节。
因此,本例的" byte_size"为5。
我们将5传递给malloc函数,并且在成功分配所需的内存空间时,它会返回一个void指针,该指针通过写入(char *)转换为char类型的指针。
然后,我们将分配的存储空间的第一个地址分配给字符指针变量" cptr"。
用C编写一个程序,使用malloc函数动态分配内存,以存储用户输入的N个整数,然后打印总和
在这个例子中,我们将使用malloc函数,byte_size将是(N * sizeof(int)),其中N的值由用户提供。
然后,我们将使用强制转换((int *)将指针转换为整数类型。
完整的代码如下。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//integer variables
int N = 0;
int sum = 0;
int i;
//integer pointer variables
int *iptr, *tmp;
//take user input
printf("Enter value of N [1-10]: ");
scanf("%d", &N);
//allocate memory
iptr = (int *) malloc (N * sizeof(int));
//check if memory allocated
if (iptr == NULL) {
printf("Unable to allocate memory space. Program terminated.\n");
return -1;
}
//take integers
printf("Enter %d integer number(s)\n", N);
for (i = 0, tmp = iptr; i < N; i++, tmp++) {
printf("Enter #%d: ", (i+1));
scanf("%d", tmp);
//compute the sum
sum += *tmp;
}
//display result
printf("Sum: %d\n", sum);
//free memory location
free(iptr);
return 0;
}
Enter value of N [1-10]: 5 Enter 5 integer number(s) Enter #1: 10 Enter #2: 20 Enter #3: 30 Enter #4: 40 Enter #5: 50 Sum: 150
上面代码的内存表示形式。
我们假设一个整数值占用2个字节的内存。
因此,在上图中,分配了10个字节的内存以保存位置1000到1009中的5个整数变量。
指针变量iptr位于存储位置8000,并为其分配了已分配空间的第一个存储位置,即1000。
我们使用一个临时整数指针" tmp"来获取用户整数并将其保存在分配的内存位置。
注意!如果我们使用iptr指针变量来获取用户整数,那么在此过程中,我们将丢失分配的内存位置地址。
因此,最好使用副本并确保分配的内存位置地址安全。
我们正在使用free()函数来释放分配的内存空间。

