一个不错的C面试问题:
你能编写一个在C中交换两个int *的函数,还能写一个对该函数的调用吗?
int a = 10, b = 20;
int* first_pointer = &a;
int* second_pointer = &b;
/* Below line should print (*first_pointer) = 10, (*second_pointer) = 20 */
printf("(*first_pointer) = %d, (*second_pointer) = %d\n",*first_pointer, *second_pointer);
/// **** Call your swap function here ****
/* Below line should print (*first_pointer) = 20, (*second_pointer) = 10 */
printf("(*first_pointer) = %d, (*second_pointer) = %d\n",*first_pointer, *second_pointer);
答案 0 :(得分:5)
功能就在这里,
void swap(int** first_pointer, int **second_pointer)
{
int *temp = *first_pointer;
*first_pointer = *second_pointer;
*second_pointer = temp;
}
函数调用在这里,
int a = 10, b = 20;
int* first_pointer = &a;
int* second_pointer = &b;
// Below will print (*first_pointer) = 10, (*second_pointer) = 20
printf("(*first_pointer) = %d, (*second_pointer) = %d\n",*first_pointer, *second_pointer);
swap(&first_pointer, &second_pointer);
// Below will print (*first_pointer) = 20, (*second_pointer) = 10
printf("(*first_pointer) = %d, (*second_pointer) = %d\n",*first_pointer, *second_pointer);