当涉及C语言中指针和动态内存分配的应用时,以下是一些实际案例:
-
动态数组分配:
#include <stdio.h> #include <stdlib.h> int main() { int n; printf("Enter the number of elements: "); scanf("%d", &n); // 使用动态内存分配创建数组 int *arr = (int *)malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed\n"); return 1; } printf("Enter %d elements:\n", n); for (int i = 0; i < n; ++i) { scanf("%d", &arr[i]); } printf("Elements entered: "); for (int i = 0; i < n; ++i) { printf("%d ", arr[i]); } // 释放动态分配的内存 free(arr); return 0; }
这个示例演示了如何使用
malloc()
函数在运行时动态分配整数数组,并在使用后释放内存以避免内存泄漏。 -
字符串操作:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; str = (char *)malloc(15 * sizeof(char)); strcpy(str, "Dynamic memory"); printf("String = %s, Address = %p\n", str, str); // 重新分配内存以扩展字符串 str = (char *)realloc(str, 25 * sizeof(char)); strcat(str, " allocation"); printf("String = %s, Address = %p\n", str, str); free(str); return 0; }
此示例演示了如何使用
malloc()
和realloc()
函数动态分配字符串,并在需要时重新分配内存以容纳更多内容。 -
链表实现:
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; int main() { struct Node *head = NULL; struct Node *temp = NULL; int n, value; printf("Enter the number of nodes: "); //输入节点数量 scanf("%d", &n); for (int i = 0; i < n; ++i) { printf("Enter the value for node %d: ", i + 1); scanf("%d", &value); struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); if (newNode == NULL) { printf("Memory allocation failed\n"); return 1; } newNode->data = value; newNode->next = NULL; if (head == NULL) { //如是无头节点 head = newNode; temp = newNode; } else { temp->next = newNode; //链条最后一个节点数据指向新存节点 temp = newNode; //更新最后一个节点数据 } } printf("Linked list values: "); temp = head; // 通过头开始从链条挨个找数据直到没有下一个。 while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } // 释放链表节点的内存,逻辑是从头部开始一个个的释放掉。 while (head != NULL) { temp = head; head = head->next; free(temp); } return 0; }
这个示例展示了如何使用指针和
malloc()
来动态创建链表节点,以及如何在程序结束时释放节点的内存以避免内存泄漏。
这些例子展示了C语言中指针和动态内存分配的实际应用,涵盖了数组、字符串和数据结构(链表)的使用。
csdn原创者:爱睡的梨
-文章会不断的更新,希望能够帮助到需要的人