在C语言中,我们可以使用数组和指针来动态分配内存。动态分配内存可以使程序更加灵活,因为它允许我们在运行时分配和释放内存。下面是数组和指针动态分配内存的示例代码:
#include
#include
int main() {
int* arr;
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// allocate memory for n integers
arr = (int*) malloc(n * sizeof(int));
// check if memory allocation is successful
if(arr == NULL) {
printf("Memory allocation failed!");
return 1; // exit
}
// get integers from user
printf("Enter %d integers: ", n);
for(int i=0; i
在上面的示例中,我们使用了malloc()函数来分配整数数组的内存。因为malloc()函数返回void类型的指针,所以我们需要将其转换为指向int类型的指针。我们还要注意在使用分配的内存后及时释放它,以避免内存泄漏。
#include
#include
int main() {
int** arr;
int n, m;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &n, &m);
// allocate memory for n pointers to integer arrays
arr = (int**) malloc(n * sizeof(int*));
// check if memory allocation is successful
if(arr == NULL) {
printf("Memory allocation failed!");