logo

Aritmètica del punter en C

Podem realitzar operacions aritmètiques sobre els punters com sumes, restes, etc. No obstant això, com sabem que el punter conté l'adreça, el resultat d'una operació aritmètica realitzada sobre el punter també serà un punter si l'altre operand és de tipus enter. En la resta de punter a punter, el resultat serà un valor enter. Les operacions aritmètiques següents són possibles al punter en llenguatge C:

rotació de l'arbre avl
  • Increment
  • Decrement
  • Addició
  • Resta
  • Comparació

Increment del punter en C

Si incrementem un punter en 1, el punter començarà a apuntar a la següent ubicació immediata. Això és una mica diferent de l'aritmètica general, ja que el valor del punter augmentarà amb la mida del tipus de dades al qual apunta el punter.

Podem recórrer una matriu utilitzant l'operació d'increment en un punter que seguirà apuntant a cada element de la matriu, realitzarà alguna operació sobre això i actualitzar-se en un bucle.

La regla per incrementar el punter es dóna a continuació:

 new_address= current_address + i * size_of(data type) 

On i és el nombre amb el qual augmenta el punter.

32 bits

Per a la variable int de 32 bits, s'incrementarà en 2 bytes.

64 bits

Per a la variable int de 64 bits, s'incrementarà en 4 bytes.

Vegem l'exemple d'incrementar la variable punter en una arquitectura de 64 bits.

 #include int main(){ int number=50; int *p;//pointer to int p=&number;//stores the address of number variable printf('Address of p variable is %u 
',p); p=p+1; printf('After increment: Address of p variable is %u 
',p); // in our case, p will get incremented by 4 bytes. return 0; } 

Sortida

 Address of p variable is 3214864300 After increment: Address of p variable is 3214864304 

Travessant una matriu utilitzant el punter

 #include void main () { int arr[5] = {1, 2, 3, 4, 5}; int *p = arr; int i; printf('printing array elements...
&apos;); for(i = 0; i<5; i++) { printf('%d ',*(p+i)); } < pre> <p> <strong>Output</strong> </p> <pre> printing array elements... 1 2 3 4 5 </pre> <h2>Decrementing Pointer in C</h2> <p>Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to the previous location. The formula of decrementing the pointer is given below:</p> <pre> new_address= current_address - i * size_of(data type) </pre> <h3>32-bit</h3> <p>For 32-bit int variable, it will be decremented by 2 bytes.</p> <h3>64-bit</h3> <p>For 64-bit int variable, it will be decremented by 4 bytes.</p> <p>Let&apos;s see the example of decrementing pointer variable on 64-bit OS.</p> <pre> #include void main(){ int number=50; int *p;//pointer to int p=&amp;number;//stores the address of number variable printf(&apos;Address of p variable is %u 
&apos;,p); p=p-1; printf(&apos;After decrement: Address of p variable is %u 
&apos;,p); // P will now point to the immidiate previous location. } </pre> <p> <strong>Output</strong> </p> <pre> Address of p variable is 3214864300 After decrement: Address of p variable is 3214864296 </pre> <h2>C Pointer Addition</h2> <p>We can add a value to the pointer variable. The formula of adding value to pointer is given below:</p> <pre> new_address= current_address + (number * size_of(data type)) </pre> <h3>32-bit</h3> <p>For 32-bit int variable, it will add 2 * number.</p> <h3>64-bit</h3> <p>For 64-bit int variable, it will add 4 * number.</p> <p>Let&apos;s see the example of adding value to pointer variable on 64-bit architecture.</p> <pre> #include int main(){ int number=50; int *p;//pointer to int p=&amp;number;//stores the address of number variable printf(&apos;Address of p variable is %u 
&apos;,p); p=p+3; //adding 3 to pointer variable printf(&apos;After adding 3: Address of p variable is %u 
&apos;,p); return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Address of p variable is 3214864300 After adding 3: Address of p variable is 3214864312 </pre> <p>As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it increments 12. But if we were using 32-bit architecture, it was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.</p> <h2>C Pointer Subtraction</h2> <p>Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a pointer will give an address. The formula of subtracting value from the pointer variable is given below:</p> <pre> new_address= current_address - (number * size_of(data type)) </pre> <h3>32-bit</h3> <p>For 32-bit int variable, it will subtract 2 * number.</p> <h3>64-bit</h3> <p>For 64-bit int variable, it will subtract 4 * number.</p> <p>Let&apos;s see the example of subtracting value from the pointer variable on 64-bit architecture.</p> <pre> #include int main(){ int number=50; int *p;//pointer to int p=&amp;number;//stores the address of number variable printf(&apos;Address of p variable is %u 
&apos;,p); p=p-3; //subtracting 3 from pointer variable printf(&apos;After subtracting 3: Address of p variable is %u 
&apos;,p); return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Address of p variable is 3214864300 After subtracting 3: Address of p variable is 3214864288 </pre> <p>You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address value.</p> <p>However, instead of subtracting a number, we can also subtract an address from another address (pointer). This will result in a number. It will not be a simple arithmetic operation, but it will follow the following rule.</p> <p>If two pointers are of the same type,</p> <pre> Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points </pre> <p>Consider the following example to subtract one pointer from an another.</p> <pre> #include void main () { int i = 100; int *p = &amp;i; int *temp; temp = p; p = p + 3; printf(&apos;Pointer Subtraction: %d - %d = %d&apos;,p, temp, p-temp); } </pre> <p> <strong>Output</strong> </p> <pre> Pointer Subtraction: 1030585080 - 1030585068 = 3 </pre> <h2>Illegal arithmetic with pointers</h2> <p>There are various operations which can not be performed on pointers. Since, pointer stores address hence we must ignore the operations which may lead to an illegal address, for example, addition, and multiplication. A list of such operations is given below.</p> <ul> <li>Address + Address = illegal</li> <li>Address * Address = illegal </li> <li>Address % Address = illegal</li> <li>Address / Address = illegal</li> <li>Address &amp; Address = illegal</li> <li>Address ^ Address = illegal</li> <li>Address | Address = illegal</li> <li> ~Address = illegal</li> </ul> <h2>Pointer to function in C</h2> <p>As we discussed in the previous chapter, a pointer can point to a function in C. However, the declaration of the pointer variable must be the same as the function. Consider the following example to make a pointer pointing to the function. <pre> #include int addition (); int main () { int result; int (*ptr)(); ptr = &amp;addition; result = (*ptr)(); printf(&apos;The sum is %d&apos;,result); } int addition() { int a, b; printf(&apos;Enter two numbers?&apos;); scanf(&apos;%d %d&apos;,&amp;a,&amp;b); return a+b; } </pre> </p><p> <strong>Output</strong> </p> <pre> Enter two numbers?10 15 The sum is 25 </pre> <h2>Pointer to Array of functions in C</h2> <p>To understand the concept of an array of functions, we must understand the array of function. Basically, an array of the function is an array which contains the addresses of functions. In other words, the pointer to an array of functions is a pointer pointing to an array which contains the pointers to the functions. Consider the following example.</p> <pre> #include int show(); int showadd(int); int (*arr[3])(); int (*(*ptr)[3])(); int main () { int result1; arr[0] = show; arr[1] = showadd; ptr = &amp;arr; result1 = (**ptr)(); printf(&apos;printing the value returned by show : %d&apos;,result1); (*(*ptr+1))(result1); } int show() { int a = 65; return a++; } int showadd(int b) { printf(&apos;
Adding 90 to the value returned by show: %d&apos;,b+90); } </pre> <p> <strong>Output</strong> </p> <pre> printing the value returned by show : 65 Adding 90 to the value returned by show: 155 </pre> <hr></5;>

Punter decreixent en C

Igual que l'increment, podem disminuir una variable punter. Si disminuïm un punter, començarà a apuntar a la ubicació anterior. La fórmula per disminuir el punter és la següent:

 new_address= current_address - i * size_of(data type) 

32 bits

Per a la variable int de 32 bits, es reduirà en 2 bytes.

64 bits

Per a la variable int de 64 bits, es reduirà en 4 bytes.

Vegem l'exemple de disminució de la variable del punter en un sistema operatiu de 64 bits.

 #include void main(){ int number=50; int *p;//pointer to int p=&amp;number;//stores the address of number variable printf(&apos;Address of p variable is %u 
&apos;,p); p=p-1; printf(&apos;After decrement: Address of p variable is %u 
&apos;,p); // P will now point to the immidiate previous location. } 

Sortida

mètode tostring
 Address of p variable is 3214864300 After decrement: Address of p variable is 3214864296 

Addició del punter C

Podem afegir un valor a la variable punter. La fórmula per afegir valor al punter es mostra a continuació:

 new_address= current_address + (number * size_of(data type)) 

32 bits

Per a la variable int de 32 bits, afegirà 2 * nombre.

64 bits

Per a la variable int de 64 bits, afegirà 4 * nombre.

convertint int a doble java

Vegem l'exemple d'afegir valor a la variable punter en una arquitectura de 64 bits.

 #include int main(){ int number=50; int *p;//pointer to int p=&amp;number;//stores the address of number variable printf(&apos;Address of p variable is %u 
&apos;,p); p=p+3; //adding 3 to pointer variable printf(&apos;After adding 3: Address of p variable is %u 
&apos;,p); return 0; } 

Sortida

 Address of p variable is 3214864300 After adding 3: Address of p variable is 3214864312 

Com podeu veure, l'adreça de p és 3214864300. Però després d'afegir 3 amb la variable p, és 3214864312, és a dir, 4*3=12 increment. Com que estem utilitzant arquitectura de 64 bits, augmenta 12. Però si estàvem utilitzant arquitectura de 32 bits, només augmentava a 6, és a dir, 2*3=6. Com que el valor sencer ocupa una memòria de 2 bytes en un sistema operatiu de 32 bits.

C Resta del punter

Igual que l'addició del punter, podem restar un valor de la variable del punter. Si resteu qualsevol número d'un punter, obtindreu una adreça. La fórmula per restar valor de la variable punter es dóna a continuació:

 new_address= current_address - (number * size_of(data type)) 

32 bits

Per a la variable int de 32 bits, restarà 2 * nombre.

64 bits

Per a la variable int de 64 bits, restarà 4 * nombre.

closca de tornada

Vegem l'exemple de restar valor de la variable punter a l'arquitectura de 64 bits.

 #include int main(){ int number=50; int *p;//pointer to int p=&amp;number;//stores the address of number variable printf(&apos;Address of p variable is %u 
&apos;,p); p=p-3; //subtracting 3 from pointer variable printf(&apos;After subtracting 3: Address of p variable is %u 
&apos;,p); return 0; } 

Sortida

 Address of p variable is 3214864300 After subtracting 3: Address of p variable is 3214864288 

Podeu veure que després de restar 3 de la variable punter, és 12 (4*3) menys que el valor de l'adreça anterior.

Tanmateix, en lloc de restar un número, també podem restar una adreça d'una altra adreça (punter). Això donarà lloc a un nombre. No serà una simple operació aritmètica, sinó que seguirà la següent regla.

Si dos punters són del mateix tipus,

 Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points 

Considereu l'exemple següent per restar un punter d'un altre.

 #include void main () { int i = 100; int *p = &amp;i; int *temp; temp = p; p = p + 3; printf(&apos;Pointer Subtraction: %d - %d = %d&apos;,p, temp, p-temp); } 

Sortida

 Pointer Subtraction: 1030585080 - 1030585068 = 3 

Aritmètica il·legal amb punters

Hi ha diverses operacions que no es poden realitzar amb els punters. Com que el punter emmagatzema l'adreça, hem d'ignorar les operacions que poden conduir a una adreça il·legal, per exemple, la suma i la multiplicació. A continuació es mostra una llista d'aquestes operacions.

  • Adreça + Adreça = il·legal
  • Adreça * Adreça = il·legal
  • Adreça % Adreça = il·legal
  • Adreça / Adreça = il·legal
  • Adreça i adreça = il·legals
  • Adreça ^ Adreça = il·legal
  • Adreça | Adreça = il·legal
  • ~Adreça = il·legal

Punter a la funció en C

Com hem comentat en el capítol anterior, un punter pot apuntar a una funció en C. Tanmateix, la declaració de la variable punter ha de ser la mateixa que la funció. Considereu l'exemple següent per fer un punter que apunti a la funció.

 #include int addition (); int main () { int result; int (*ptr)(); ptr = &amp;addition; result = (*ptr)(); printf(&apos;The sum is %d&apos;,result); } int addition() { int a, b; printf(&apos;Enter two numbers?&apos;); scanf(&apos;%d %d&apos;,&amp;a,&amp;b); return a+b; } 

Sortida

usos del sistema operatiu
 Enter two numbers?10 15 The sum is 25 

Punter a la matriu de funcions en C

Per entendre el concepte de matriu de funcions, hem d'entendre la matriu de funció. Bàsicament, una matriu de la funció és una matriu que conté les adreces de les funcions. En altres paraules, el punter a una matriu de funcions és un punter que apunta a una matriu que conté els punters a les funcions. Considereu l'exemple següent.

 #include int show(); int showadd(int); int (*arr[3])(); int (*(*ptr)[3])(); int main () { int result1; arr[0] = show; arr[1] = showadd; ptr = &amp;arr; result1 = (**ptr)(); printf(&apos;printing the value returned by show : %d&apos;,result1); (*(*ptr+1))(result1); } int show() { int a = 65; return a++; } int showadd(int b) { printf(&apos;
Adding 90 to the value returned by show: %d&apos;,b+90); } 

Sortida

 printing the value returned by show : 65 Adding 90 to the value returned by show: 155