C/C++ 中指標的應用
訪問陣列元素
我們可以使用指標訪問陣列元素。
在 C 語言中
示例
#include <stdio.h>
int main() {
int a[] = { 60, 70, 20, 40 };
printf("%d\n", *(a + 1));
return 0;
}輸出
70
在 C++ 語言中
示例
#include <iostream>
using namespace std;
int main() {
int a[] = { 60, 70, 20, 40 };
cout<<*(a + 1);
return 0;
}輸出
70
動態記憶體分配
為了動態分配記憶體,我們使用指標。
在 C 語言中
示例
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, *ptr;
ptr = (int*) malloc(3 * sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
*(ptr+0)=1;
*(ptr+1)=2;
*(ptr+2)=3;
printf("Elements are:");
for(i = 0; i < 3; i++) {
printf("%d ", *(ptr + i));
}
free(ptr);
return 0;
}輸出
Elements are:1 2 3
在 C++ 語言中
示例
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int i, *ptr;
ptr = (int*) malloc(3 * sizeof(int));
if(ptr == NULL) {
cout<<"Error! memory not allocated.";
exit(0);
}
*(ptr+0)=1;
*(ptr+1)=2;
*(ptr+2)=3;
cout<<"Elements are:";
for(i = 0; i < 3; i++) {
cout<< *(ptr + i);
}
free(ptr);
return 0;
}輸出
Elements are:1 2 3
將引數作為引用傳遞給函式
我們可以使用指標在函式中按引用傳遞引數以提高效率。
在 C 語言中
示例
#include <stdio.h>
void swap(int* a, int* b) {
int t= *a;
*a= *b;
*b = t;
}
int main() {
int m = 7, n= 6;
swap(&m, &n);
printf("%d %d\n", m, n);
return 0;
}輸出
6 7
在 C++ 語言中
示例
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
int t= *a;
*a= *b;
*b = t;
}
int main() {
int m = 7, n= 6;
swap(&m, &n);
cout<< m<<n;
return 0;
}輸出
67
為了實現諸如連結串列、樹等資料結構,我們也可以使用指標。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP