অ্যারে উপাদান অ্যাক্সেস করতে
আমরা পয়েন্টার ব্যবহার করে অ্যারে উপাদান অ্যাক্সেস করতে পারি।
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
লিঙ্কড লিস্ট, ট্রির মতো ডেটা স্ট্রাকচার বাস্তবায়ন করতে আমরা পয়েন্টারও ব্যবহার করতে পারি।