我遇到了问题“C 程序在数组中输入用户定义的元素而不定义数组大小”。有谁知道解决这个问题的C程序代码吗?
我尝试获取 C 程序编码中的逻辑,并且希望在数组中得到一个简单的 C 程序代码,而无需使用用户定义的数组元素定义数组大小。
在 C 中,我们可以使用动态内存分配来创建数组,这允许我们在不指定数组大小的情况下创建数组。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int size, i;
// Get the size of the array from the user
printf("Enter the size of the array: ");
scanf("%d", &size);
// Allocate memory for the array dynamically
arr = (int *)malloc(size * sizeof(int));
// Check if memory allocation is successful
if (arr == NULL) {
printf("Memory allocation failed. Exiting program.\n");
return 1;
}
// Enter elements into the array
printf("Enter %d elements:\n", size);
for (i = 0; i < size; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Display the entered elements
printf("\nEntered elements in the array are:\n");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
// Free the dynamically allocated memory
free(arr);
return 0;
}
此外,使用
free
释放动态分配的内存以避免内存泄漏。