阅读量:136
在C语言中,current指针通常用于表示当前正在处理的数据结构元素
-
链表遍历: 在遍历链表时,
current指针用于指向当前正在处理的节点。例如:struct Node { int data; struct Node* next; }; void printList(struct Node* head) { struct Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } } -
动态数组: 在使用动态数组(如数组的大小可以在运行时改变)时,
current指针可以用于指向当前正在处理的元素。例如:#include#include int main() { int n, i; printf("Enter the number of elements: "); scanf("%d", &n); int* arr = (int*)malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed."); return 1; } printf("Enter the elements: "); for (i = 0; i < n class="hljs-built_in">scanf("%d", arr + i); } printf("The elements are: "); for (i = 0; i < n class="hljs-built_in">printf("%d ", *(arr + i)); } free(arr); return 0; } -
字符串操作: 在处理字符串时,
current指针可以用于遍历字符串的每个字符。例如:#include#include void reverseString(char* str) { int length = strlen(str); char* current = str; char* last = str + length - 1; char temp; while (current< last xss=removed xss=removed xss=removed class="hljs-type">int main() { char str[] = "Hello, World!"; reverseString(str); printf("Reversed string: %s\n", str); return 0; }
这些只是current指针在C语言中的一些常见用法。实际上,current指针可以在任何需要遍历或处理数据结构元素的场景中使用。