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