在C語言中,current
指針通常用于表示當(dāng)前正在處理的數(shù)據(jù)結(jié)構(gòu)元素
鏈表遍歷:
在遍歷鏈表時(shí),current
指針用于指向當(dāng)前正在處理的節(jié)點(diǎn)。例如:
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;
}
}
動(dòng)態(tài)數(shù)組:
在使用動(dòng)態(tài)數(shù)組(如數(shù)組的大小可以在運(yùn)行時(shí)改變)時(shí),current
指針可以用于指向當(dāng)前正在處理的元素。例如:
#include<stdio.h>
#include <stdlib.h>
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; i++) {
scanf("%d", arr + i);
}
printf("The elements are: ");
for (i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
free(arr);
return 0;
}
字符串操作:
在處理字符串時(shí),current
指針可以用于遍歷字符串的每個(gè)字符。例如:
#include<stdio.h>
#include<string.h>
void reverseString(char* str) {
int length = strlen(str);
char* current = str;
char* last = str + length - 1;
char temp;
while (current< last) {
temp = *current;
*current = *last;
*last = temp;
current++;
last--;
}
}
int main() {
char str[] = "Hello, World!";
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
這些只是current
指針在C語言中的一些常見用法。實(shí)際上,current
指針可以在任何需要遍歷或處理數(shù)據(jù)結(jié)構(gòu)元素的場(chǎng)景中使用。