பாடம் 2 / 3 · Pointers · படிக்க 2 min · புதுப்பிக்கப்பட்டது
Call பண்ணவங்களோட variable-ஐ மாத்துறது
Pointers-ஆல கிடைக்கிற முதல் நன்மை — நீங்க கொடுத்ததை மாத்தக்கூடிய functions.
Pointers-னால கிடைக்கிற முதல் பெரிய நன்மை — நாம கொடுத்த variable-ஐ function-க்குள்ள இருந்தே மாற்ற முடியும். ஒரு variable-ஐ நேரடியாகக் கொடுத்தா, அதோட copy தான் function-க்கு கிடைக்கும்; உள்ள மாற்றினாலும் original மாறாது. அதுக்கு பதிலா அதோட address-ஐ கொடுத்தா, function அந்த address-ஐ பயன்படுத்தி original variable-ஐயே மாற்ற முடியும்.
#include <stdio.h>
void double_it(int *n)
{
*n = *n * 2;
}
int main(void)
{
int x = 21;
double_it(&x);
printf("%d\n", x); /* 42 */
return 0;
}
பிரபலமானது: ரெண்டு values-ஐ மாத்துறது
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
int x = 1, y = 2;
swap(&x, &y);
printf("%d %d\n", x, y); /* 2 1 */
return 0;
}
Note
Pointers இல்லாம இந்த function-ஐ C-ல எழுதவே முடியாது. அதனாலதான் கிட்டத்தட்ட எல்லா C courses-லயும் swap-ஐ example-ஆ எடுத்துக்குறாங்க — pointers உண்மையிலேயே ஏன் தேவைப்படுதுன்னு புரிய வைக்கிற ஒரு சின்ன, தெளிவான problem இது.
ஒண்ணுக்கு மேல பதில் திருப்பி தருறது
/* A function can only return one value —
pointers let it deliver several. */
void min_and_max(int arr[], int n, int *min, int *max)
{
*min = arr[0];
*max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < *min) *min = arr[i];
if (arr[i] > *max) *max = arr[i];
}
}
Warning
எதையும் point பண்ணாம இருக்குற pointer-தான் C-ல crash வர்றதுக்கு ரொம்ப சாதாரண காரணம். Pointer-க்கு இப்போதைக்கு valid target இல்லன்னா, அதை NULL-ஆ வெச்சுக்கோங்க; dereference பண்ணுறதுக்கு முன்னாடி NULL-ஆ இருக்கான்னு check பண்ணுங்க. NULL-ஐ dereference பண்ணினா program crash ஆகிடும் — அமைதியா memory-ஐ கெடுத்துக்கிட்டு இருக்குறத விட அது பரவாயில்லை.
swap ஏன் int a-க்கு பதிலா int *a எடுக்கணும்?
Create a free account to save your progress, or sign in.