给定一个字符串字面量数组,请反转数组。
例子:
Input : arr[] = {"Coding", "Never", "Fail", "Me"}
Output : arr[] = {"Me", "Fail", "Never", "Coding"}
Input : arr[] = {"welcome", "to", "geeksforgeeks"}
Output : arr[] = {"geeksforgeeks", "to", "welcome"}
这个想法是创建一个指针数组,在其中存储字符串字面量。为了反转数组,我们从begin和end开始,然后将两个指针移向彼此。移动时,我们会不断交换指针。
// C program to reverse an array of strings
#include
#include
void PrintArray(char* arr[], int n)
{
for (int i = 0; i < n; i++) {
printf("%s ", arr[i]);
}
}
void ReverseArray(char* arr[], int n)
{
char* temp;
// Move from begin and end. Keep
// swapping strings.
int j = n - 1;
for (int i = 0; i < j; i++) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;
}
}
int main()
{
char* arr[] = { "Coding", "never", "fail", "me" };
int n = sizeof(arr) / sizeof(arr[0]);
PrintArray(arr, n);
printf("\n");
ReverseArray(arr, n);
PrintArray(arr, n);
return 0;
}
输出:
Coding never fail me
me fail never Coding
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。