Documente online.
Zona de administrare documente. Fisierele tale
Am uitat parola x Creaza cont nou
 HomeExploreaza
upload
Upload




Using Pointers for Variable Parameters in C

software


Using Pointers for Variable Parameters

Most C programmers first need to use pointers for variable parameters. Suppose you have a simple procedure in Pascal that swaps two integer values:



program samp;
var
a,b:integer;

procedure swap(var i,j:integer);
var t:integer;
begin
t:=i;
i:=j;
j:=t;
end

begin
a:=5;
b:=10;
writeln(a,b);
swap(a,b);
writeln(a,b);
end


Because this code uses variable parameters, it swaps the values a and b correctly.



C has no formal mechanism for passing variable parameters: It passes everything by value. Enter and execute the following code and see what happens:



#include <stdio.h>

void swap(int i, int j)


void main()



No swapping takes place. The values of a and b are passed to swap, but no values are returned.

To make this function work correctly, you must use pointers, as shown below:



#include <stdio.h>

void swap(int *i, int *j)


void main()



To get an idea of what this code does, print it out, draw the two integers a and b, and enter 5 and 10 in them. Now draw the two pointers i and j, along with the integer t. When swap is called, it is passed the addresses of a and b. Thus, i points to a (draw an arrow from i to a) and j points to b (draw another arrow from b to j). Because the pointers have been established, *i is another name for a, and *j is another name for b. Now run the code in swap. When the code uses *i and *j, it really means a and b. When the function completes, a and b have been swapped.

Suppose you accidentally forget the & when the swap function is called, and that the swap line accidentally looks like this: swap(a,b);. This causes a segmentation fault. When you leave out the &, the value of a is passed instead of its address. Therefore, i points to an invalid location in memory and the system crashes when *i is used.

This is also why scanf crashes if you forget &--- scanf is using pointers to put the value it reads back into the variable you have passed. Without &, scanf is pas


Document Info


Accesari: 1285
Apreciat: hand-up

Comenteaza documentul:

Nu esti inregistrat
Trebuie sa fii utilizator inregistrat pentru a putea comenta


Creaza cont nou

A fost util?

Daca documentul a fost util si crezi ca merita
sa adaugi un link catre el la tine in site


in pagina web a site-ului tau.




eCoduri.com - coduri postale, contabile, CAEN sau bancare

Politica de confidentialitate | Termenii si conditii de utilizare




Copyright Contact (SCRIGROUP Int. 2024 )