#include <stdio.h>
#include <stdlib.h>
int main() {
char *arr = NULL;
int size, new_size;
// 动态分配初始内存
printf("Enter the initial size of the array: ");
scanf("%d", &size);
arr = (char *)malloc(size * sizeof(char));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// 初始化数组
for (int i = 0; i < size; i++) {
arr[i] = 'a'+i;
}
// 输出初始数组
printf("Initial array: ");
for (int i = 0; i < size; i++) {
printf("%c ", arr[i]);
}
printf("\n");
// 根据用户输入调整数组大小
printf("Enter the new size of the array: ");
scanf("%d", &new_size);
// 重新分配内存
char * back_arr = arr;
arr = (char *)realloc(arr, new_size * sizeof(char));
if (arr == NULL) {
printf("Memory reallocation failed\n");
return 1;
}
// 如果新大小大于旧大小,初始化新元素
if (new_size > size) {
for (int i = 0; i < new_size; i++) {
arr[i] = 'A'+i;
}
}
// 输出调整后的数组
printf("Resized array: ");
for (int i = 0; i < new_size; i++) {
printf("%c ", arr[i]);
}
printf("\n");
// 释放内存
free(arr);
return 0;
}
这是一个练习,实现了动态分配内存.
标签:arr,int,练习,C语言,char,printf,new,指针,size From: https://blog.csdn.net/2402_87656226/article/details/144546161