8-1. Pointer 小考試
1. 某科技業筆試題
int a[] = {1,2,3,4,5,6};
int *p = a;
*(p++) += 100;
*(++p) += 100;
for ( int i = 0 ; i < 6 ; i++ )
cout << a[i] << " ";
(a) 1 2 3 4 5 6
(b) 101 2 103 4 5 6
(c) 101 102 3 4 5 6
(d) 1 102 3 104 5 6
(e) 以上皆非
2. 進階筆試
int a[] = {1,2,3,4,5,6};
int *p = &a[3];
int *p2 = a+5;
*p = 100;
*p2 = *p2 - *p;
for ( int i = 0 ; i < 6 ; i++ )
cout << a[i] << " ";
(a) 1 2 3 4 5 6
(b) 101 2 103 4 5 6
(c) 101 102 3 4 5 6
(d) 1 102 3 104 5 6
(e) 以上皆非 填充
3. 深度筆試
void swap( int a , int b ){
int t = a;
a = b;
b = t;
}
int main(){
int x = 3, y = 5;
swap( x, y );
cout<<"x = "<<x<<" ,y = "<<y;
}
要怎麼改,才能達到交換效果
4. 困難筆試
int a[] = {1,2,3,4,5,6};
int *p = &a[3];
int **pp = &p;
*pp = a;
*p = 100;
for ( int i = 0 ; i < 6 ; i++ )
cout << a[i] << " ";
(a) 100 2 3 4 5 6
(b) 1 100 3 4 5 6
(c) 1 2 3 4 5 6
(d) 1 2 100 4 5 6
(e) 1 2 3 100 5 6
解答:
- (b) 101 2 103 4 5 6
- (e) 以上皆非,正解是 1 2 3 100 5 -94
答案
void swap( int *a , int *b ){ int t = *a; *a = *b; *b = t; } int main(){ int x = 3, y = 5; swap( &x, &y ); cout<<"x = "<<x<<" ,y = "<<y; }
- (a) 100 2 3 4 5 6
自己實作一個printArray()的function
#include<bits/stdc++.h>
using namespace std;
void printArray(int *arr,int length){
for(int i =0; i<length;i++){
cout<<arr[i]<<" ";
}
return;
}
int main(){
int N = 5; // 陣列長度
int numbers[N];
for(int i =0; i<N;i++){
numbers[i]=i; //初始化
}
cout<<"numbers的記憶體address: "<<numbers<<endl;
cout<<"numbers裡面的資料: ";
printArray(numbers,N);
}