<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>FireTeam &#187; Programmazione C</title>
	<atom:link href="http://www.fireteam.it/category/programmazione/programmazione-c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fireteam.it</link>
	<description>#fuoco@AzzurraNet</description>
	<lastBuildDate>Tue, 16 Mar 2010 15:55:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Introduzione al Calcolo Scientifico</title>
		<link>http://www.fireteam.it/2009/09/introduzione-al-calcolo-scientifico/</link>
		<comments>http://www.fireteam.it/2009/09/introduzione-al-calcolo-scientifico/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 20:41:36 +0000</pubDate>
		<dc:creator>saverio</dc:creator>
				<category><![CDATA[Programmazione C]]></category>
		<category><![CDATA[calcolo scientifico]]></category>

		<guid isPermaLink="false">http://www.fireteam.it/?p=596</guid>
		<description><![CDATA[Caratteristiche fondamentali del software scientifico:
Efficienza, Accuratezza, Affidabilità, Modularità, API standard, Portabilità, Facilità d’uso, Facilità di manutenzione
Problem Solving:
Formulazione del problema P, Descrizione di P mediante un modello matematico:M(P) approssimazione di M(P) mediante metodi numerici Mh(P), Sviluppo dell’algoritmo risolutivo Mh(P),Implementazione in uno specifico ambiente di calcolo
Da che cosa dipende il tempo di esecuzione di un software?
Un’ implementazione [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.fireteam.it/wp-content/uploads/2009/09/calcolo-massa-corporea.png"><img class="alignright size-full wp-image-598" title="calcolatrice" src="http://www.fireteam.it/wp-content/uploads/2009/09/calcolo-massa-corporea.png" alt="calcolatrice" width="190" height="208" /></a>Caratteristiche fondamentali del software scientifico:<br />
Efficienza, Accuratezza, Affidabilità, Modularità, API standard, Portabilità, Facilità d’uso, Facilità di manutenzione</p>
<p>Problem Solving:<br />
Formulazione del problema P, Descrizione di P mediante un modello matematico:M(P) approssimazione di M(P) mediante metodi numerici Mh(P), Sviluppo dell’algoritmo risolutivo Mh(P),Implementazione in uno specifico ambiente di calcolo</p>
<h2>Da che cosa dipende il tempo di esecuzione di un software?</h2>
<p>Un’ implementazione efficiente dipende oltre che dal numero di operazioni floating-point anche dagli accessi alla MEMORIA<br />
T1 = Nmem x tmem + N flop x t flop    mem=tempo di accesso alla memoria, flop=tempo operazioni floating point<br />
Nmem &amp; Nflop: dipende dall&#8217;algoritmo; tmem &amp; tflop: dipende dalla tecnologia.</p>
<p><span id="more-596"></span>Ridurre il numero di accessi alla memoria, ridurre il tempo di accesso alla memoria &#8211;&gt; riuso dei dati nei registri<br />
La complessità di tempo dell’algoritmo (Nflop) e la velocità del processore (tflop) sono fisse</p>
<h2>Vantaggi e caratteristiche delle BLAS</h2>
<p>Modularità: sw scritto in termini di building blocks; Chiarezza: codice più breve e più leggibile;<br />
Efficienza: implementazioni ottimizzate da parte dei costruttori di computer; Portabilità: interfacce standard, dipendenza dall’architettura incapsulata in BLAS; Affidabilità, robustezza: gestione accurata di “dettagli” algoritmici e implementativi e di situazioni di errore (es: overflow)</p>
<p>Traffico parassita:<br />
Parametro di valitazione del traffico parassita: q = #accessi alla memoria / #operazioni floating point<br />
SAXPY: y=y+ax  &#8211;&gt; preleva x (n accessi), preleva y (n accessi), preleva a (1 accesso), calcolo = (2n op. fl.p.), riponi y (n accessi)<br />
q = m/f = (3n+1) / (2n)<br />
DOT: a = x(trasposto) * y &#8211;&gt; preleva x (n accessi), preleva y (n accessi), calcolo = (2n op. fl.p.), riponi in a (1 accesso)<br />
q = m/f = (2n+1) / (2n)  &#8211;&gt; quasi 1.<br />
GAXPY: y=y+Mx  &#8211;&gt; preleva y (n accessi), preleva M (n^2 accessi), preleva x (n accessi), calcolo y+Mx = (2n^2 op. fl.p.), riponi y (n accessi)<br />
q = m/f = (3n+n^2) / (2n^2)<br />
Strategia: Suddivisione della matrice in blocchi di dimensione pari alla cache</p>
<h2>Tecnica di LOOP UNROLLING</h2>
<p>Lo “srotolamento” del ciclo consistente nel modificare il controllo del ciclo e nel replicare opportunamente le istruzioni all’interno del ciclo viene detto Tecnica di LOOP UNROLLING<br />
Vantaggi del loop unrolling: Utilizzo ottimale dei processori con architettura pipelined, riduzione dell’overhead del ciclo di iterazione riduzione del numero di trasferimenti fra i vari livelli memoria, aumento delle operazioni concorrenti;L’overhead del programma e il numero di trasferimenti di dati dai livelli più bassi di memoria ai registri, si riducono di un fattore proporzionale alla nuova lunghezza del ciclo (profondità dell’unrolling); Svantaggi del loop unrolling: unrolling;Aumento della memoria destinata al programma; Perdita della generalità del codice</p>
<p>Una matrice si dice simmetrica quando A[i][j] = A[j][i]</p>
<p>Cholesky e matrici simmetriche:<br />
Applicando l&#8217;algoritmo di Gauss senza pivoting ad una matrice simmetrica, abbiamo che le sottomatrici attive sono anch’esse simmetriche. Questo è vero in generale e si dimostra.<br />
Si può sfruttare la simmetria considerando solo un triangolo della matrice.<br />
Se si usa il pivoting parziale si perde la simmetria della matrice.<br />
Quindi, in generale, l&#8217;utilizzo di una tecnica di pivoting nell’algoritmo di Gauss NON CONSENTE di sfruttare, in termini di efficienza computazionale la simmetria della matrice<br />
In quali condizioni si può evitare il pivoting?<br />
- Matrici a diagonale dominante (al generico passo K, le sottomatrici attive sono a diagonale dominante – il pivot starebbe sempre sulla diagonale)<br />
- Matrici simmetriche e definite positive (una matrice è def positiva se det(A)&gt;0) (criterio di Sylvester)<br />
Se una matrice è simmetrica, la fattorizzazione A=LU (senza pivoting) si specializza in A=LDL^T (A=LU, D^-U=LT quindi U=DL^T, A=LDL^T) L=matrice triangolare inferiore(moltiplicatori), D=matrice diagonale(elementi diagonali di U))<br />
Come si specializza la fattorizzazione LDL^T di una matrice simmetrica e definita positiva?<br />
Esiste un’unica matrice L triangolare inferiore tale che: A=LL^T<br />
A=LLT &#8211;&gt; Algoritmo di Cholesky    T(chol)=O((n^3)/6))=Tgauss(n)/2<br />
L’Algoritmo di Cholesky ha una complessità di TEMPO che è la metà di quella dell’Algoritmo di Gauss!!<br />
A è simmetrica allora si memorizza solo una metà degli elementi; L è triangolare allora si memorizzano solo gli elementi non nulli<br />
L’Algoritmo di Cholesky ha una complessità di SPAZIO che è la metà di quella dell’Algoritmo di Gauss!!<br />
Quando è possibile applicare la fattorizzazione LL^T ad una matrice simmetrica e a diagonale dominante? ovvero quando una matrice simmetrica a diagonale dominante è anche definita positiva?<br />
- non singolare (det(A)&gt;0)<br />
- simmetrica<br />
- a diagonale dominante<br />
- ha gli elementi sulla diag non negativi</p>
<p>Matrici TOEPLITZ ottenute l’una da una rotazione dell’altra.</p>
<p>Matrice bidiagonale:<br />
- bidiagonale inferiore se: a(i,j)=0 per j&gt;i e per i&gt;j+1<br />
- bidiagonale superiore se: a(i,j)=0 per i&gt;j e per j&gt;i+1</p>
<p>Matrice tridiagonale: se a(i,j)=0 per |i-j|&gt;1<br />
In una matrice tridiagonale di dim nxn gli elementi che bisogna effettivamente conservare sono quelli delle tre diagonali cioè sono 3n-2.</p>
<p>Matrice a banda: ampiezza di banda inferiore=p, ampiezza di banda superiore=q  se a(i,j)=0 per i&gt;j+p e per j&gt;i+q</p>
<p>Si consideri la seguente matrice a banda 6&#215;6 con p=1 e q=2</p>
<p>a(1,1) a(1,2) a(1,3)<br />
a(2,1) a(2,2) a(2,3) a(2,4)<br />
a(3,2) a(3,3) a(3,4) a(3,5)<br />
a(4,3) a(4,4) a(4,5) a(4,6)<br />
a(5,4)  a(5,5) a(5,6)<br />
a(6,5) a(6,6)</p>
<p>questa matrice viene memorizzata nel seguente modo:</p>
<p>*            *     a(1,3) a(2,4) a(3,5) a(4,6)<br />
*         a(1,2) a(2,3) a(3,4) a(4,5) a(5,6)<br />
a(1,1) a(2,2) a(3,3) a(4,4) a(5,5) a(6,6)<br />
a(2,1) a(3,2) a(4,3) a(5,4) a(6,5)    *<br />
ossia l’elemento a(i,j) è memorizzato nella colonna di posto j e nella riga di posto 3+i-j=q+1+i-j</p>
<p>Fattorizzazione LU senza pivoting di una matrice tridiagonale e risoluzione dei sistemi lineari associati:<br />
si ha che i fattori L ed U di una matrice tridiagonale (che ammette fattorizzazione LU) sono matrici bidiagonali</p>
<p>Fattorizzazione LU di una matrice partizionata a blocchi:<br />
se abbiamo una matrice tridiagonale (w=p+q+1), conduce alle matrici bidiagonali dove<br />
L-&gt; w=p+1=1+1=2; U-&gt; w=q+1=1+1=2<br />
Gli elementi di U e di A appartenenti alla banda superiore coincidono; gli elementi di L da determinare sono L2 e L3; gli elementi di U da determinare sono le matrici diagonali U1, U2, U3</p>
<p>Come si specializzano gli algoritmi di Forward e Back Substitution per matrici a blocchi?<br />
Si risolve Lz=y O(n^2) operazioni poi Ux=z (z è stato ricavato precedentemente)</p>
<h3>ALGORITMO FORWARD:</h3>
<p>for i=1 to n do<br />
y[i]=b[i]-L[i]y[i-1]<br />
endfor<br />
(L[1]y[0]=0)</p>
<h3>ALGORITMO DI BACK</h3>
<p>for i=N to 1 do<br />
U[i]x[i]=y[i]-F[i]y[i+1]<br />
endfor<br />
(F[n]x[n+1]=0)</p>
<h2>FATTORIZZAZIONE LU DI UNA MATRICE A BLOCCHI</h2>
<p>Supponiamo di avere una matrice partizionata in 9=3&#215;3 blocchi<br />
(A11, A12, A13, A21, A22, A23, A31, A32, A33).<br />
Sappiamo che A=LU.<br />
Effettuando il prodotto:<br />
A11=L11 U11     A12=L11 U12                  A13=L11 U13<br />
A21=L21 U11     A22=L21 U12+L22 U22    A23=L21 U13+L22 U23<br />
A31=L31 U11     A32=L31 U12+L32 U22    A33=L31 U13+L32 U23+L33 U33<br />
Da queste uguaglianze si ricavano le espressioni per il calcolo dei blocchi di L e di U<br />
Ricordando l’algoritmo di fattorizzazione LU abbiamo che fissiamo la colonna e la riga e sotto abbiamo la matrice attiva.<br />
<span style="text-decoration: underline;">PASSO1:</span><br />
- fattorizzazione LU del “pannello verticale”<br />
- calcolo un pannello orizzontale di U<br />
- aggiorna la matrice attiva<br />
alla fine del passo 1 abbiamo:<br />
- il primo pannello verticale di L<br />
- il primo pannello orizzontale di U</p>
<p>Nel <span style="text-decoration: underline;">PASSO 2</span> scendiamo di un livello quindi alla fine avremo:<br />
- il secondo pannello verticale di L<br />
- il secondo pannello orizzontale di U</p>
<h2>ALGORITMO LU BLOCK PARTITIONED</h2>
<p>A dcomposta in nxn blocchi di dim nbxnb</p>
<p>For k=1, n step nb do<br />
- applica la fatt LU al pannello A(k:n,k:k+nb-1)<br />
- calcola il pannello U(k:k+nb-1, k+nb:n)<br />
- aggiorna la matrice attiva</p>
<h4>Sistema sparso:</h4>
<p>Un sistema di equazioni lineari si dice “sparso” se ha molti coefficienti nulli; il grado di sparsità è SP=numero di coefficienti nulli / numero totale di coefficienti. In generale in un sistema dove A=nxm e p è il numero di coefficienti non nulli: SP=(n x m) – p / n x m. Dunque 0=&lt;SP&gt;=1, e più SP è prossimo a 1 maggiore è il grado si sparsità della matrice.</p>
<h2>I metodi iterativi:</h2>
<p>Per sistemi con elevato grado di sparsità l’algoritmo di Gauss non è molto efficiente in quanto non solo effettua operazioni su coefficienti nulli ma può anche portarli a essere non nulli. Per tale motivo c’è bisogno di metodi alternativi detti iterativi, che lavorano sui coefficienti non nulli. Per tale motivo è anche possibile implementare opportune tecniche di memorizzazione di matrici sparse per migliorare la complessità di spazio. Una di queste tecniche è quella dei tre vettori – CSR -  R contenente gli elementi non nulli per riga della matrice A, IC contente l’indice di colonna in A degli elementi presenti in R, J contente la posizione in R del primo elemento non nullo per ciascuna riga di A.</p>
<h3>Metodi iterativi: Jacobi</h3>
<p>Procedimento iterativo:a partire da arbitrari valori iniziali delle incognite x1(^0), x2(^0), x3(^0) , esegue una sequenza di iterazioni in ognuna delle quali si calcolano nuovi valori per le incognite utilizzando i valori calcolati nella iterazione precedente. Dunque dato un sistema Ax=b:<br />
ad ogni passo i=1…n   -&gt;   xi(^k+1)=1/aii (bi – sum per j=1 to n con j!=i di (aij  xj(^k) )).<br />
La complessità di tale metodo per il calcolo delle n componenti ad ciascuna iterazione è<br />
Tjac(n)=n(2n-1) operazioni=n^2 operazioni, ma siccome le operazioni vengono effettuate solo sui p coefficienti non nulli (SP=1- p/n^2) allora Tjac(n)= p operazioni= n^2 (1-SP) operazioni</p>
<h3>Metodi iterativi: Gauss-Seidel</h3>
<p>Il procedimento è simile a quella di Jacobi, la differenza sostanziale è che mentre in Jacobi ad ogni iterazione k il nuovo valore delle incognite è calcolato utilizzando unicamente i valori x1(^k-1), x2(^k-1), x3(^k-1) calcolati all’iterata precedente, in Gauss Seidel invece ad ogni passo k nel calcolare una xi(^k) possono essere utilizzati i valori xj(^k), per j&lt;i e xj(^k-1) per j&gt;=i (ossia i valori delle soluzioni del passo precedente k-1). Ad esempio nel calcolare x2(^k) viene utilizzato x1(^k) e x2(^k-1), x3(^k-1). . Dunque dato un sistema Ax=b:<br />
ad ogni passo i=1…n   -&gt;   xi(^k+1)=1/aii (bi – [sum per j=1 to i-1 di (aij  xj(^k+1))] &#8211; [sum per j=i+1 to n di (aij  xj(^k))]). Analogamente a quanto accade per jacobi, Tgs(n)= p operazioni= n^2 (1-SP) operazioni.</p>
<h3>Convergenza e consistenza dei metodi iterativi:</h3>
<p>In generale Gauss-Seidel converge più velocemente alla soluzione rispetto a Jacobi. Tuttavia i metodi iterativi non sempre convergono alla soluzione del sistema.<br />
Un metodo iterativo si dice convergente se la successione generata dal metodo è convergente, qualunque siano i valori iniziali, cioè se lim (k-&gt;inf) di xi(^k)= xi(^*) per ogni i=1…n e per ogni xi(^0) approssimazione iniziale. Se il metodo converge allora esso convergerà alla soluzione; per tale caratteristica i metodi si dicono consistenti, ossia che quando converge esso converge alla soluzione. Un metodo iterativo si dive convergente se ||C||&lt;1, dove ||C|| indica la norma della matrice C nxn dei coefficienti cij del sistema. Inoltre Jacobi converge con certezza anche quando la matrice è a diagonale strettamente dominante. Tali condizioni tuttavia sono solo sufficienti non necessarie in quanto il metodo può convergere anche se queste condizioni non sono soddisfatte.</p>
<h3>Efficienza di un metodo iterativo:</h3>
<p>La complessità totale di un metodo iterativo è: Ttot(n)= k Tit(n); dove k indica il numero di iterazioni eseguite (parametro dipendente dalla velocità di convergenza) e Tit(n) indica la complessità di tempo di 1 iterazione (parametro dipendente dal costo di ciascuna iterazione). Sia per Jacobi che per Gauss Seidel il numero di operazioni effettuate è relativo solo ai coefficienti p non nulli dunque T(n)= p operazioni= n^2 (1-SP) operazioni.</p>
<h3>Velocità di convergenza:</h3>
<p>||C|| oltre a garantire la convergenza serve a determinare la velocità di convergenza dato che  quanto più piccolo è questo valore tanto più velocemente si convergerà alla soluzione ottima.<br />
Indicando con eps(^k)=x(^k)- x(^*) l’errore di troncamento ammissibile alla k-esima iterazione (differenza all’iterata k tra l’approssimazione e la soluzione), dove || eps(^k)||&lt;=||C^k || ||eps(^0)||, è possibili trovare il numero minimo di iterazioni per avere || eps(^k)||&lt;tol (tol=tolleranza desiderata): k=[ ln (tol) – ln (||eps(^0)||) ]/ ln (||C||).<br />
La convergenza del metodo equivale alla convergenza a 0 dell’errore di troncamento alla k-esima iterazione, cioè di di eps(^k).</p>
<h3>Criteri di arresto:</h3>
<p>Il metodo iterativo può essere arrestato o agendo sull’errore assoluto e in tal caso il criterio d’arresto sarà: ||x(^k) – x*||&lt;=tol, dove in generale tol=10(^-m) è l’approssimazione corretta a m cifre decimali; oppure sull’errore relativo ||x(^k) – x*|| / ||x*||&lt;=tol, dove in generale tol=10(^-m) è l’approssimazione corretta a m-1 cifre significative; tuttavia utilizzando questi criteri si presuppone la conoscenza della soluzione x* ottima e quindi la necessità di determinare stime calcolabili dell’errore ad ogni iterazione. Mentre criteri d’arresto effettivamente utilizzabili sono quelli basate su quantità già calcolate e quindi basati o sulla stima dell’errore assoluto ||x(^k+1) – x(^k)||&lt;=tol; o sull’errore relativo ||x(^k) – x(^k-1)|| / ||x(^k-1)||&lt;=tol.<br />
Altro criterio di arresto, aggiuntivo e/o sostitutivo, è quello basato sull’impostazione di un numero massimo Maxit di iterazioni che permette l’arresto anche nel caso in cui il metodo non converge e limita il costo computazionale del procedimento iterativo.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fireteam.it/2009/09/introduzione-al-calcolo-scientifico/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementazione C di Heap Sort</title>
		<link>http://www.fireteam.it/2009/07/implementazione-c-di-heap-sort/</link>
		<comments>http://www.fireteam.it/2009/07/implementazione-c-di-heap-sort/#comments</comments>
		<pubDate>Fri, 10 Jul 2009 21:20:14 +0000</pubDate>
		<dc:creator>saverio</dc:creator>
				<category><![CDATA[Programmazione C]]></category>
		<category><![CDATA[sort]]></category>

		<guid isPermaLink="false">http://www.fireteam.it/?p=475</guid>
		<description><![CDATA[L&#8217; heapsort è un algoritmo di ordinamento iterativo ed in-place proposto da Williams nel 1964, che si basa su strutture dati ausiliarie.
L&#8217; heapsort per eseguire l&#8217;ordinamento, utilizza una struttura chiamata heap (mucchio); un heap è rappresentabile con un albero binario in cui tutti i nodi seguono una data proprietà, detta priorità. Esso è completo almeno [...]]]></description>
			<content:encoded><![CDATA[<p>L&#8217; heapsort è un algoritmo di ordinamento iterativo ed in-place proposto da Williams nel 1964, che si basa su strutture dati ausiliarie.</p>
<blockquote><p>L&#8217; heapsort per eseguire l&#8217;ordinamento, utilizza una struttura chiamata heap (mucchio); un heap è rappresentabile con un albero binario in cui tutti i nodi seguono una data proprietà, detta priorità. Esso è completo almeno fino al penultimo livello dell&#8217;albero e ad ogni nodo corrisponde uno ed un solo elemento.</p>
<p>In uno heap decrescente (utilizzato per ordinare ad esempio un array in senso crescente) ogni nodo padre contiene un valore maggiore o uguale a quello dei suoi due figli diretti, di conseguenza risulterà maggiore anche di tutti i nodi che si trovano nel sottoalbero di cui esso è la radice; questo non implica affatto che nodi a profondità maggiore contengano valori minori di quelli a profondità minore.</p>
<p>Quindi in ogni istante, in un heap decrescente, la radice contiene il valore maggiore.</p>
<p>Questa struttura è molto usata, in particolare, per l&#8217;ordinamento di array.</p>
<p>In questo caso si considera come radice l&#8217;elemento iniziale di indice 1; inoltre i figli di un nodo con indice j, avranno indice rispettivamente 2j, quello sinistro, 2j+1 quello destro.</p>
<p><span id="more-475"></span>Per comprendere meglio il funzionamento dell&#8217;algoritmo è bene capire che gli elementi che si trovano nella seconda metà dell&#8217;array rappresenteranno foglie dello heap e quindi esse saranno già al loro posto giusto; non vi è infatti alcun elemento dopo di esse.</p>
<p>&#8230;tratto da wikipedia</p></blockquote>
<h2>Implementazione Iterativa di Heap Sort</h2>
<p>L&#8217;algoritmo che ordina in senso crescente inizia creando uno heap decrescente. Per ogni iterazione si copia la radice (primo elemento dell&#8217;array) in fondo all&#8217;array stesso, eseguendo uno scambio di elementi. L&#8217;algoritmo poi ricostruisce uno heap di n &#8211; 1 elementi spostando verso il basso la nuova radice, e ricomincia con un altro scambio (tra il primo elemento dell&#8217;array e quello in posizione n &#8211; 1), eseguendo un ciclo che considera array di dimensione progressivamente decrescente.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#define MAX 20</span>
&nbsp;
<span style="color: #993333;">int</span> sinistro<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> destro<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> padre<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">/</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
stampavettore<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;=</span>n <span style="color: #339933;">;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d &quot;</span><span style="color: #339933;">,</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> riempivettore<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;inserire l'elemento %d dell'array('-1' per terminare): &quot;</span><span style="color: #339933;">,</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 scanf<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d&quot;</span><span style="color: #339933;">,</span>vettore<span style="color: #339933;">+</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">!=</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">return</span> i<span style="color: #339933;">-</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> scambia<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>n1<span style="color: #339933;">,</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>n2<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> temp<span style="color: #339933;">;</span>
&nbsp;
 temp <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>n1<span style="color: #339933;">;</span>
 <span style="color: #339933;">*</span>n1 <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>n2<span style="color: #339933;">;</span>
 <span style="color: #339933;">*</span>n2 <span style="color: #339933;">=</span> temp<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> heapify<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span><span style="color: #993333;">int</span> heapsize<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> l<span style="color: #339933;">,</span>r<span style="color: #339933;">,</span>maggiore<span style="color: #339933;">,</span>violazione<span style="color: #339933;">=</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>violazione<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 l <span style="color: #339933;">=</span> sinistro<span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 r <span style="color: #339933;">=</span> destro<span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>l <span style="color: #339933;">&lt;=</span> heapsize<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#91;</span>l<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;</span> vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 maggiore <span style="color: #339933;">=</span> l<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span> 
 <span style="color: #009900;">&#123;</span>
 maggiore <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>r <span style="color: #339933;">&lt;=</span> heapsize<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#91;</span>r<span style="color: #009900;">&#93;</span><span style="color: #339933;">&gt;</span>vettore<span style="color: #009900;">&#91;</span>maggiore<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 maggiore <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>maggiore <span style="color: #339933;">!=</span> i<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 scambia<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,&amp;</span>vettore<span style="color: #009900;">&#91;</span>maggiore<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 i<span style="color: #339933;">=</span>maggiore<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
 violazione <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> buildheap<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span><span style="color: #993333;">int</span> heapsize<span style="color: #339933;">,</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>n<span style="color: #339933;">/</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">&gt;=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 heapify<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>i<span style="color: #339933;">,</span>heapsize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
heapsort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span>heapsize<span style="color: #339933;">;</span>
&nbsp;
 heapsize<span style="color: #339933;">=</span>n<span style="color: #339933;">;</span>
 buildheap<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>heapsize<span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span>n <span style="color: #339933;">;</span> i<span style="color: #339933;">&gt;</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 scambia<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>vettore<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,&amp;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 heapsize<span style="color: #339933;">--;</span>
 heapify<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>heapsize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> vettore<span style="color: #009900;">&#91;</span>MAX<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> n<span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/*numero di elementi*/</span>
&nbsp;
 n<span style="color: #339933;">=</span>riempivettore<span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 heapsort<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 stampavettore<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Si può dimostrare che la complessità asintotica massima dell&#8217;heap sort è O(nlogn). Tuttavia, in generale (e soprattutto per array quasi ordinati) altri algoritmi con la medesima complessità asintotica, per esempio quick sort o merge sort, ottengono migliori prestazioni. Per array di piccole dimensioni è addirittura più veloce l&#8217;insertion sort nonostante abbia una complessità di O(n^2))</p>
<h2>Implementazione Ricorsiva di Heap Sort</h2>
<p>Qui vi è l&#8217;implementazione ricorsiva in linguaggio C di Heap Sort</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#define MAX 20</span>
&nbsp;
<span style="color: #993333;">int</span> sinistro<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> destro<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> padre<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">/</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
stampavettore<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;=</span>n <span style="color: #339933;">;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d &quot;</span><span style="color: #339933;">,</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> riempivettore<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;inserire l'elemento %d dell'array('-1' per terminare): &quot;</span><span style="color: #339933;">,</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 scanf<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d&quot;</span><span style="color: #339933;">,</span>vettore<span style="color: #339933;">+</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">!=</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">return</span> i<span style="color: #339933;">-</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> scambia<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>n1<span style="color: #339933;">,</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>n2<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> temp<span style="color: #339933;">;</span>
&nbsp;
 temp <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>n1<span style="color: #339933;">;</span>
 <span style="color: #339933;">*</span>n1 <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>n2<span style="color: #339933;">;</span>
 <span style="color: #339933;">*</span>n2 <span style="color: #339933;">=</span> temp<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> heapify<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span><span style="color: #993333;">int</span> heapsize<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> l<span style="color: #339933;">,</span>r<span style="color: #339933;">,</span>maggiore<span style="color: #339933;">;</span>
&nbsp;
 l <span style="color: #339933;">=</span> sinistro<span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 r <span style="color: #339933;">=</span> destro<span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>l <span style="color: #339933;">&lt;=</span> heapsize<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#91;</span>l<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;</span> vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 maggiore <span style="color: #339933;">=</span> l<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
 maggiore <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>r <span style="color: #339933;">&lt;=</span> heapsize<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#91;</span>r<span style="color: #009900;">&#93;</span><span style="color: #339933;">&gt;</span>vettore<span style="color: #009900;">&#91;</span>maggiore<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 maggiore <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>maggiore <span style="color: #339933;">!=</span> i<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 scambia<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,&amp;</span>vettore<span style="color: #009900;">&#91;</span>maggiore<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 heapify<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>maggiore<span style="color: #339933;">,</span>heapsize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> buildheap<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span><span style="color: #993333;">int</span> heapsize<span style="color: #339933;">,</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>n<span style="color: #339933;">/</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">&gt;=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 heapify<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>i<span style="color: #339933;">,</span>heapsize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
heapsort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span>heapsize<span style="color: #339933;">;</span>
&nbsp;
 heapsize<span style="color: #339933;">=</span>n<span style="color: #339933;">;</span>
 buildheap<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>heapsize<span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span>n <span style="color: #339933;">;</span> i<span style="color: #339933;">&gt;</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 scambia<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>vettore<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,&amp;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 heapsize<span style="color: #339933;">--;</span>
 heapify<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>heapsize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> vettore<span style="color: #009900;">&#91;</span>MAX<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> n<span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/*numero di elementi*/</span>
&nbsp;
 n<span style="color: #339933;">=</span>riempivettore<span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 heapsort<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 stampavettore<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.fireteam.it/2009/07/implementazione-c-di-heap-sort/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementazione C del Quicksort</title>
		<link>http://www.fireteam.it/2009/07/implementazione-c-del-quicksort/</link>
		<comments>http://www.fireteam.it/2009/07/implementazione-c-del-quicksort/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 20:55:13 +0000</pubDate>
		<dc:creator>saverio</dc:creator>
				<category><![CDATA[Programmazione C]]></category>
		<category><![CDATA[ordinamento]]></category>
		<category><![CDATA[sort]]></category>

		<guid isPermaLink="false">http://www.fireteam.it/?p=428</guid>
		<description><![CDATA[Quicksort è un ottimo algoritmo di ordinamento ricorsivo in place che, come merge sort, si basa sul paradigma divide et impera. La base del suo funzionamento è l&#8217;utilizzo ricorsivo della procedura partition: preso un elemento da una struttura dati (es. array) si pongono gli elementi minori a sinistra rispetto a questo e gli elementi maggiori [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.fireteam.it/wp-content/uploads/2009/07/Sorting_quicksort_anim.gif"><img class="alignright size-full wp-image-436" title="FunzionamentoQuicksort" src="http://www.fireteam.it/wp-content/uploads/2009/07/Sorting_quicksort_anim.gif" alt="FunzionamentoQuicksort" width="280" height="214" /></a>Quicksort è un ottimo algoritmo di ordinamento ricorsivo in place che, come merge sort, si basa sul paradigma divide et impera. La base del suo funzionamento è l&#8217;utilizzo ricorsivo della procedura partition: preso un elemento da una struttura dati (es. array) si pongono gli elementi minori a sinistra rispetto a questo e gli elementi maggiori a destra.</p>
<blockquote><p>Il Quicksort, termine che tradotto letteralmente in italiano indica ordinamento rapido, è l&#8217;algoritmo di ordinamento che ha, in generale, prestazioni migliori tra quelli basati su confronto; è stato sottoposto a un&#8217;analisi matematica approfondita ed estremamente precisa, tanto che le sue prestazioni sono state comprese a fondo e il suo comportamento è stato descritto in modo molto accurato.</p>
<p><span id="more-428"></span></p>
<p>I risultati ottenuti in fase di analisi sono stati verificati sperimentalmente in modo esteso e l&#8217;algoritmo di base è stato migliorato al punto da diventare il metodo ideale per un gran numero di applicazioni pratiche.</p>
<p>tratto da wikipedia</p></blockquote>
<p>Per la sua estrema facilità è stato scelto in molte librerie di linguaggi, come il C, di implementare di base una funzione che effettui l&#8217;ordinamento del Quicksort&#8230; però il nostro professore di programmazione vuole vedere il codice sorgente <img src='http://www.fireteam.it/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Codice C Quicksort</h2>
<p>Eccolo qua:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#define MAX 20</span>
&nbsp;
stampavettore<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;=</span>n <span style="color: #339933;">;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d &quot;</span><span style="color: #339933;">,</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> riempivettore<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
 i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;inserire l'elemento %d dell'array('-1' per terminare): &quot;</span><span style="color: #339933;">,</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 scanf<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d&quot;</span><span style="color: #339933;">,</span>vettore<span style="color: #339933;">+</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">!=</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">return</span> i<span style="color: #339933;">-</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> scambia<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>n1<span style="color: #339933;">,</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>n2<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> temp<span style="color: #339933;">;</span>
&nbsp;
 temp <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>n1<span style="color: #339933;">;</span>
 <span style="color: #339933;">*</span>n1 <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>n2<span style="color: #339933;">;</span>
 <span style="color: #339933;">*</span>n2 <span style="color: #339933;">=</span> temp<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> partiziona<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> p<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> r<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> x <span style="color: #339933;">=</span> vettore<span style="color: #009900;">&#91;</span>p<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> p<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> j <span style="color: #339933;">=</span> r<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> itera <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">;</span> vettore<span style="color: #009900;">&#91;</span><span style="color: #339933;">--</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&gt;</span> x <span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">;</span> vettore<span style="color: #009900;">&#91;</span><span style="color: #339933;">++</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&lt;</span> x <span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&lt;</span> j<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 scambia<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,&amp;</span>vettore<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
 itera <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>itera<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">return</span> j<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> quicksort<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> p<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> r<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> q<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>p <span style="color: #339933;">&lt;</span> r<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 q <span style="color: #339933;">=</span> partiziona<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>p<span style="color: #339933;">,</span>r<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 quicksort<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>p<span style="color: #339933;">,</span>q<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 quicksort<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>q<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>r<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> vettore<span style="color: #009900;">&#91;</span>MAX<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> n<span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/*numero di elementi*/</span>
&nbsp;
 n<span style="color: #339933;">=</span>riempivettore<span style="color: #009900;">&#40;</span>vettore<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 quicksort<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 stampavettore<span style="color: #009900;">&#40;</span>vettore<span style="color: #339933;">,</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h2>Caratteristiche del Quicksort</h2>
<table border="0">
<tbody>
<tr>
<th>Struttura dati</th>
<td>Variabile</td>
</tr>
<tr>
<th>Caso pessimo temporalmente</th>
<td><span class="texhtml">Θ(<em>n</em><sup>2</sup>)</span></td>
</tr>
<tr>
<th>Caso ottimo temporalmente</th>
<td><span class="texhtml">Θ(<em>n</em>log<em>n</em>)</span></td>
</tr>
<tr>
<th>Caso medio temporalmente</th>
<td><span class="texhtml">Θ(<em>n</em>log<em>n</em>)</span> confronti</td>
</tr>
<tr>
<th>Caso pessimo spazialmente</th>
<td>Dipende dalle implementazioni</td>
</tr>
<tr>
<th>Ottimale</th>
<td>Spesso</td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.fireteam.it/2009/07/implementazione-c-del-quicksort/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Array Multidimensionali in C</title>
		<link>http://www.fireteam.it/2009/07/array-multidimensionali-in-c/</link>
		<comments>http://www.fireteam.it/2009/07/array-multidimensionali-in-c/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 15:50:48 +0000</pubDate>
		<dc:creator>saverio</dc:creator>
				<category><![CDATA[Programmazione C]]></category>
		<category><![CDATA[puntatori]]></category>
		<category><![CDATA[stringhe]]></category>
		<category><![CDATA[vettori]]></category>

		<guid isPermaLink="false">http://www.fireteam.it/?p=367</guid>
		<description><![CDATA[Questo articolo tratta la gestione delle stringhe e, in generale, dei vettori multidimensionali nel linguaggio C.
Allocazione di memoria del vettore
Sappiamo che nel linguaggio c dichiariamo un vettore con l&#8217;istruzione
int vett[n];
in questo modo creiamo un vettore chiamato vett di n elementi:
vett[0] , vett[1] , &#8230; , vett[n-1]
Supponiamo, con n=5, di riempire il vettore in questo modo:



10
11
12
13
14



Risulterà [...]]]></description>
			<content:encoded><![CDATA[<p>Questo articolo tratta la gestione delle stringhe e, in generale, dei vettori multidimensionali nel linguaggio C.</p>
<h2>Allocazione di memoria del vettore</h2>
<p>Sappiamo che nel linguaggio c dichiariamo un vettore con l&#8217;istruzione</p>
<p>int vett[n];</p>
<p>in questo modo creiamo un vettore chiamato vett di n elementi:</p>
<p>vett[0] , vett[1] , &#8230; , vett[n-1]</p>
<p>Supponiamo, con n=5, di riempire il vettore in questo modo:</p>
<table border="1">
<tbody>
<tr>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
</tbody>
</table>
<p>Risulterà che:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"> vett<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">10</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>vett
 vett<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">11</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>vett<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span>
 vett<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">12</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>vett<span style="color: #339933;">+</span><span style="color: #0000dd;">2</span>
 vett<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">13</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>vett<span style="color: #339933;">+</span><span style="color: #0000dd;">3</span>
 vett<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">4</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">14</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>vett<span style="color: #339933;">+</span><span style="color: #0000dd;">4</span></pre></td></tr></table></div>

<p><span id="more-367"></span></p>
<p>Inoltre supponiamo di aver fatto girare al computer il programma,<br />
avremo alcuni indirizzi se stampiamo:</p>
<p>804400008 = vett<br />
804400012 = vett+1<br />
804400016 = vett+2<br />
804400020 = vett+3<br />
804400024 = vett+4</p>
<h2>Passare il vettore ad una funzione</h2>
<p>Ora che sappiamo come viene creato un vettore in memoria affrontiamo<br />
il problema di passare il vettore nelle funzioni. Supponiamo la funzione:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> funzione<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>n <span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
 vettore<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">+=</span> <span style="color: #0000dd;">20</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>che aggiunge 20 ad ogni elemento del vettore. Quale sarà la chiamata giusta<br />
da fare nel programma chiamante?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 .
 .
 .
 <span style="color: #202020;">funzione</span><span style="color: #009900;">&#40;</span>vett<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 .
 .
 .
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Perchè passiamo &#8220;vett&#8221; e non &#8220;&amp;vett&#8221;?<br />
Il contenuto di &#8220;vett&#8221; non è altro che un indirizzo&#8230; il primo elemento del<br />
vettore è &#8220;*vett&#8221; oppure &#8220;vett[0]&#8220;.<br />
Quindi con questa chiamata non facciamo altro che passare per valore alla<br />
funzione un indirizzo che è proprio l&#8217;indirizzo del nostro vettore <img src='http://www.fireteam.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Praticamente nella funzione viene dichiarato un puntatore ad intero chiamato<br />
&#8220;vettore&#8221;. La dichiarazione è</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> <span style="color: #339933;">*</span>vettore</pre></td></tr></table></div>

<p>Quindi in vettore mettiamo l&#8217;indirizzo che nell&#8217;esempio è 804400008.<br />
All&#8217;intrno della funzione risulterà che:</p>
<p>vettore   = 804400008          &lt;&#8211; indirizzo<br />
*vettore   = 10                 &lt;&#8211; contenuto di vett[0]<br />
*vettore+1 = 11                 &lt;&#8211; contenuto di vett[1]</p>
<p>Questo è il motivo che nel linguaggio C non è obbligatorio definire la<br />
dimensione del vettore!</p>
<h2>STAMPA SU VIDEO DI UN VETTORE v DI n ELEMENTI</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> StampaVettore<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> n<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> <span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span> Vettore = ( &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>n<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">;</span> i<span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%.2f %s&quot;</span><span style="color: #339933;">,</span>v<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;, &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%.2f %s <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>v<span style="color: #009900;">&#91;</span>n<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span><span style="color: #ff0000;">&quot; );&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h2>STAMPA SU VIDEO DI UNA MATRICE M DI n RIGHE ED m COLONNE</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> StampaMatrice<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> n<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> m<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> <span style="color: #339933;">**</span>M<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span>j<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>i<span style="color: #339933;">&lt;</span>n<span style="color: #339933;">;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>j<span style="color: #339933;">&lt;</span>m<span style="color: #339933;">;</span>j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%.2f %s&quot;</span><span style="color: #339933;">,</span>M<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;   &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.fireteam.it/2009/07/array-multidimensionali-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gestione dei File nel linguaggio C</title>
		<link>http://www.fireteam.it/2009/07/gestione-dei-file-nel-linguaggio-c/</link>
		<comments>http://www.fireteam.it/2009/07/gestione-dei-file-nel-linguaggio-c/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 16:25:58 +0000</pubDate>
		<dc:creator>ivan</dc:creator>
				<category><![CDATA[Programmazione C]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[file]]></category>

		<guid isPermaLink="false">http://www.fireteam.it/?p=384</guid>
		<description><![CDATA[Input /output e gestione dei file
Iniziamo la lezione dicendo subito che per INPUT/OUTPUT si intende l’ insieme delle operazioni di
ingresso ed uscita, ossia lo scambio di informazioni tra il programma e le unita’ periferiche del
calcolatore.
Nel linguaggio C l’ I/O e’ interamente implementato mediante funzioni della libreria standard.
Il linguaggio C vede i file come un flusso [...]]]></description>
			<content:encoded><![CDATA[<h2>Input /output e gestione dei file</h2>
<p>Iniziamo la lezione dicendo subito che per INPUT/OUTPUT si intende l’ insieme delle operazioni di<br />
ingresso ed uscita, ossia lo scambio di informazioni tra il programma e le unita’ periferiche del<br />
calcolatore.<br />
Nel linguaggio C l’ I/O e’ interamente implementato mediante funzioni della libreria standard.<br />
Il linguaggio C vede i file come un flusso (stream) sequenziale di byte. Uno stream dal punto di vista<br />
tecnico e’ una implementazione software in grado di gestire le informazioni relative all’interazione a<br />
basso livello con la periferica associata, in modo che il programma possa trascurare di che periferica si<br />
tratti.<br />
Ogni file termina con un marcatore di fine file detto<br />
EOF( end-of-file) definito in &lt;stdio.h&gt; come una costante simbolica uguale a -1.</p>
<p><span id="more-384"></span></p>
<h2>I file e gli stream</h2>
<p>Un file e&#8217; una sequenza di lunghezza non prefissata di valori dello stesso tipo.<br />
Quando un file viene aperto sara’ associato uno stream . Tre file e i loro rispettivi stream, lo standard di<br />
input, lo standard di output, lo standard error (stdin, stdout, stderr) , sono aperti automaticamente<br />
quando inizia l’esecuzione di un programma.<br />
Lo stream dello standard di input consente ad un programma di ricevere input dalla tastiera. (puo’<br />
essere rediretto su altre periferiche).<br />
Lo stream dello standard di output consente ad un programma di di scrivere sul video della<br />
macchina.(puo’ essere rediretto su altre periferiche)<br />
Lo stream dello standard di errore consente ad un programma di scrivere sul video della macchina.<br />
(non puo’ essere rediretto su altre periferiche).<br />
Un programma C puo’ servirsi degli stream standard ; basta che vi compaia la direttiva<br />
#include&lt;stdio.h&gt;<br />
Gli stream forniscono un canale di comunicazione tra i file ed i programmi.<br />
L’apertura di un file restituisce un puntatore ad una struttura FILE (definita in &lt;stdio.h&gt;) che contiene<br />
le informazioni utilizzate per elaborare il file. La struttura FILE ha un file descriptor (descrittore di<br />
file), cioe’ l’indice di un vettore del S.O. chiamata open file table (tabella dei file aperti). Ogni<br />
elemento del vettore contiene un file control block o FCB (blocco di controllo del file) il quale viene<br />
utilizzato dal S.O. per amministrare un particolare file.<br />
Consideriamo due tipi di file i file di testo ed i file binari; i primi utilizzati quando l&#8217;informazione da<br />
memorizzarvi e&#8217; di tipo testo cioe&#8217; sequenze di caratteri; i secondi quando si vuole memorizzare nel file<br />
dati di un generico tipo (interi,strutture ecc&#8230;).</p>
<h2>Il puntatore al file</h2>
<p>Attraverso la definizione<br />
FILE *fp;<br />
viene permessa l’associazione di un identificatore del programma ad un file, che si trova in memoria<br />
secondaria.<br />
Con la sola definizione, fp e’ soltanto una “variabile di tipo FILE”; l’effettiva associazione avviene in<br />
fase di apertura del file.<br />
Il puntatore fp punta ad informazioni che descrivono alcune caratteristiche dei file come il nome, lo<br />
stato e la posizione corrente.<br />
Scopo del puntatore al file e’ quello di identificare uno specifico file su disco e viene usato dal flusso<br />
associato per svolgere in modo corretto le operazioni di input/output.</p>
<h2>Apertura di un file</h2>
<p>Avendo la definizione FILE *fp;<br />
Per aprire il file di avente nome “dati.in” ed associarlo ad fp si esegue la seguente operazione di<br />
apertura:<br />
fp = fopen(“dati.in”, “r”);<br />
Vediamo che l’access mode “r” implica l’apertura del file dati.in, presente in memoria secondaria, in<br />
modalita’ di sola lettura.<br />
Il prototipo della fopen() e’:<br />
FILE *fopen(const char *nome_del_file, const char *modo);<br />
nome_del_file deve essere un puntatore ad una stringa di caratteri che costituisce un nome valido<br />
secondo quanto definito dal S.O. e puo’ includere un percorso (path); la stringa a cui punta il modo<br />
definisce la modalita’ con cui sara’ aperto il file.<br />
La fopen() restituisce un puntatore al file di tipo FILE oppure un puntatore nullo nel caso si verifichi un<br />
errore.<br />
Si puo’ pensare che quando il file viene aperto, vi sia un cursore che segna il punto di accesso<br />
all’interno del file (viene letto un dato in corrispondenza della posizione del cursore). Cosi all’apertura<br />
del file il cursore si posiziona all’inizio del file; quando viene letto un dato, il cursore va alla posizione<br />
successiva; alla prossima lettura viene letto il dato successivo eccetera.<br />
Un file puo’ essere aperto per operazioni di sola scrittura e sono necessarie le istruzioni:<br />
FILE *fp;<br />
fp = fopen(“dati.in”, “w”);<br />
e’ possibile aprire sia file di testo che file binari.<br />
Notare che conviene sempre nei programmi verificare che il file sia stato aperto correttamente (cioe’<br />
che la funzione fopen() abbia avuto successo).<br />
Per fare cio’ si deve usare, nel caso il file in uso fosse dati.in, un frammento di codice come il seguente:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">FILE <span style="color: #339933;">*</span>fp<span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> nome_del_file <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> “dati_in”
 fp <span style="color: #339933;">=</span> fopen<span style="color: #009900;">&#40;</span>nome_del_file<span style="color: #339933;">,</span> “r”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>fp<span style="color: #339933;">!=</span>NULL<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #808080; font-style: italic;">/* istruzioni di utilizzo del file*/</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span>“\n impossibile aprire il file”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>La istruzione di uscita exit(1) viene utilizzata soltanto se si e’ nel main() altrimenti se si e’ all’interno di<br />
una altra funzione, al suo posto si utilizza la return.</p>
<h2>Chiusura di un file</h2>
<p>Per chiudere un file precedentemente aperto con la fopen() si utilizza la funzione fclose().<br />
E’ molto importante chiudere tutti i file aperti in un programma prima che questi termini la sua<br />
esecuzione. Infatti l’operazione di chiusura scrive nel file fisico corrispondente possibili dati che siano<br />
rimasti nel buffer di scrittura.<br />
Il prototipo della fclose e’:<br />
int fclose(FILE *fp);<br />
in cui fp e’ il puntatore che restituisce la fopen().<br />
La fclose() tenta di chiudere il file puntato da fp e restituisce il valore 0 nel caso in cui la chiusura sia<br />
terminata con successo (altrimenti un valore diverso da 0 nel caso di chiusura fallita). Comunque di<br />
solito la fclose() da errore soltanto se un disco e’ stato tolto dall’unita’ di lettura prematuramente<br />
oppure quando non vi e’ piu’ spazio libero.</p>
<h2>Le modalita’ di accesso dei file</h2>
<p>La modalita’ di accesso (access mode) indica come si dovra’ collegare un file ad un identificatore del<br />
programma e come si potra’ usare quel file.<br />
Come visto sopra la modalita’ “r” implica che il file venga aperto soltanto in lettura (solo per leggerne i<br />
dati), se il file esiste naturalmente.<br />
Mentre con “w” si indica (ad esempio nella fopen(“dati.in”, “w”);) di aprire il file dati.in in modalita’<br />
di scrittura. Se il file esiste, nella memoria secondaria, i dati in esso contenuti saranno persi e sostituiti<br />
con i nuovi dati che vi scriveremo; se il file non esiste viene creato.<br />
Vediamo una lista con i valori previsti per l’argomento modo nella fopen(.. , ..)</p>
<ul>
<li> “r”                          Apre un file testuale esistente per sola lettura, posizionando il cursore all’inizio del file;</li>
<li> “w”                          Apre un file testuale per sola scrittura: se il file gia’ esiste i dati in esso contenuti vengono perduti; se il file non esiste ne viene creato uno nuovo;</li>
<li> “a”                          Apre un file di testuale esistente per scrittura, in modalita’ append; il cursore viene posizionato alla fine del file e si puo’ scrivere nel file solo in coda ai dati gia’ presenti; i dati gia presenti non vengono cancellati;</li>
<li> “r+”                         Apre un file testuale esistente in lettura e scrittura; il cursore viene posto all’inizio;</li>
<li> “w+”                         Apre un file testuale per lettura e scrittura; se il file gia’ esiste i dati in esso contenuti vengono perduti; se il file non esiste, ne viene creato uno nuovo;</li>
<li> “a+”                         Apre un file testuale in modalita’ append; se il file non esiste, ne viene creato uno nuovo; si possono leggere tutti i dati del file; si possono scrivere dati solo in fondo al file.</li>
<li> “rb”                         Apre un file binario esistente per sola lettura, posizionando il cursore all’inizio;</li>
<li> “wb”                         Apre un file binario per sola scrittura; se il file gia’ esiste i dati in esso contenuti vengono persi; se il file non esiste , ne viene creato uno nuovo;</li>
<li> “ab”                         Apre o crea un file binario per scrittura in modalita’ append; il cursore viene posizionato alla fine del file e si puo’ scrivere nel file solo in coda ai dati gia’ presenti;</li>
<li> “rb+”                        Apre un file binario esistente in lettura e scrittura</li>
<li> “wb+”                        Apre o crea un file binario in lettura e scrittura</li>
<li> “ab+”                        Apre o crea in modalita’ append un file binario.</li>
</ul>
<h2>Creazione di un file sequenziale</h2>
<p>Vediamo un esempio di programma in cui utilizzeremo le funzioni fopen() ed fclose():</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* creare un file sequenziale*/</span>
 <span style="color: #339933;">#include&lt;stdio.h&gt;</span>
 <span style="color: #993333;">int</span> main <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> numero_di_conto<span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> nome<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">31</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">float</span> saldo<span style="color: #339933;">;</span>
 FILE <span style="color: #339933;">*</span>fpunt<span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/* puntatore al file clienti.dat*/</span>
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>fpunt <span style="color: #339933;">=</span> fopen<span style="color: #009900;">&#40;</span>“clienti.<span style="color: #202020;">dat</span>”<span style="color: #339933;">,</span> “w”<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> <span style="color: #339933;">=</span> NULL<span style="color: #009900;">&#41;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span>“Il file non puo’ essere aperto\n”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span>“Inserite il numero di conto<span style="color: #339933;">,</span> il nome<span style="color: #339933;">,</span> ed il saldo.\n”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span>“inserite EOF per finire gli inserimenti\n”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">?</span>”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 scanf<span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d<span style="color: #339933;">%</span>s<span style="color: #339933;">%</span>f”<span style="color: #339933;">,&amp;</span>numero_di_conto<span style="color: #339933;">,</span> nome<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>saldo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>feof<span style="color: #009900;">&#40;</span>stdin<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 fprintf<span style="color: #009900;">&#40;</span>fpunt<span style="color: #339933;">,</span>”<span style="color: #339933;">%</span>d<span style="color: #339933;">%</span>s<span style="color: #339933;">%</span><span style="color:#800080;">.2f</span>\n”<span style="color: #339933;">,</span> numero_di_conto<span style="color: #339933;">,</span> nome<span style="color: #339933;">,</span> saldo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">?</span>”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 scanf<span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d<span style="color: #339933;">%</span>s<span style="color: #339933;">%</span>f”<span style="color: #339933;">,&amp;</span>numero_di_conto<span style="color: #339933;">,</span> nome<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>saldo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 fclose<span style="color: #009900;">&#40;</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Questo programma creera’ un semplice file ad accesso sequenziale di nome clienti.dat<br />
Nella schermata di input dovremo inserire ad esempio<br />
? 10 roberta 10,5<br />
? 11 roberto 22<br />
? 12 jennifer 30<br />
?<br />
ed EOF per terminare l’immissione di nuovi dati.<br />
Come anticipato FILE *fpunt stabilisce che fpunt e’ un puntatore ad una struttura FILE.<br />
La fprintf e’ analoga alla funzione printf soltanto che la fprintf scrive nel file invece che sul video.<br />
Il programma richiedera’ all’utente di immettere per ogni record i vari campi; quando viene conclusa<br />
l’immissione dei dati richiedera’ un end-of-file.<br />
L’end-of-file per i diversi sistemi di computer e’ segnalato in lista (Sistema,Combinazione di tasti):<br />
Sistemi UNIX: &lt;return&gt;&lt;ctrl&gt;d<br />
PC IBM e compatibili: &lt;ctrl&gt;z<br />
Macintosh: &lt;ctrl&gt;d<br />
VAX(VMS): &lt;ctrl&gt;z</p>
<p>La riga di codice<br />
while (!feof(stdin))<br />
Usa la funzione feof per determinare se sia stato impostato EOF per il file al quale punta stdin.<br />
EOF indichera’ al programma che non ci sono piu’ dati da elaborare.<br />
Il nostro programma non mostra come i dati dei record appaiono realmente all’interno del file. Per fare<br />
cio’ e verificare quindi la correttezza dei dati creati necessita un programma che leggera’ il file e ne<br />
visualizza il contenuto.<br />
Funzioni di lettura e scrittura<br />
Si distinguono in due categorie lettura e scrittura per carattere e lettura e scrittura per linee (stringhe).<br />
Fra le prime consideriamo la funzione fputc e la funzione fgetc.<br />
La funzione fputc ha il seguente prototipo:<br />
int fputc (int c , FILE *fpunt);<br />
questa funzione preleva un carattere c e lo stampa(scrive) nel file fpunt,(file puntato da fpunt) nella<br />
posizione del cursore; naturalmente il file deve essere stato precedentemente aperto con la funzione<br />
fopen( ), ed fpunt e’ il puntatore restituito da quest’ultima funzione.<br />
Il carattere c viene convertito in un unsigned char nella fputc.<br />
Restituisce il carattere letto (il codice) oppure EOF (se la stampa e’ andata male)<br />
La funzione fgetc ha il seguente prototipo:<br />
int fgetc(FILE *fpunt);<br />
la funzione restituisce (convertito in intero) il carattere letto dal file fpunt “file precedentemente aperto<br />
con la fopen()”;<br />
il cursore avanza di un dato (il prossimo da leggere); in caso vi sia errore viene restituito EOF.<br />
Nella lettura e scrittura per linee consideriamo la funzione fgets ed fputs ; con la fgets si legge al piu’<br />
una intera linea da un file passato per argomento “file precedentemente aperto tramite la funzione<br />
fopen()”.<br />
Il prototipo della funzione e’:<br />
char *fgets (char *strin, int n, FILE *fpunt);<br />
con questa funzione viene letto, dal file fpunt, una sequenza di caratteri, fermandosi al newline (oppure<br />
fermandosi ad n caratteri letti od all’EOF) e memorizza i caratteri letti nell’array strin; la fgets<br />
restituisce l’array letto oppure NULL se ha incontrato EOF.<br />
L’eventuale EOL (‘\n’) letto verra’ incluso nella stringa risultante.<br />
Con il parametro n si specifica il numero massimo di caratteri da leggere; se la linea del file contiene<br />
un numero di caratteri maggiore di n i caratteri in eccesso non verranno letti.<br />
La funzione fputs ha il seguente prototipo:<br />
int fputs(const char *strin, FILE *fpunt);<br />
e stampa nel file fpunt(precedentemente aperto tramite la fopen(..) ) i caratteri contenuti nella stringa<br />
strin; se la stampa e’ andata a buon fine restituisce il valore 0 , altrimenti un numero diverso da zero.<br />
Esempio<br />
Nel seguente programma la funzione fputs() scrive nel file prova delle stringhe lette dalla tastiera,<br />
tramite la funzione gets(), e passategli come parametro.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdio.h&quot;</span>
 <span style="color: #339933;">#include &quot;stdlib.h&quot;</span>
 <span style="color: #339933;">#include &quot;string.h&quot;</span>
 <span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span><span style="color: #993333;">char</span> strin<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">81</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 FILE <span style="color: #339933;">*</span>fpunt<span style="color: #339933;">;</span>
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>fpunt<span style="color: #339933;">=</span>fopen<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;prova&quot;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;w&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">==</span>NULL<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Errore nella lettura del file<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">do</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;inserite una stringa e premere INVIO per uscire:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 gets<span style="color: #009900;">&#40;</span>strin<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 strcat<span style="color: #009900;">&#40;</span>strin<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/*aggiunta di un newline*/</span>
 fputs<span style="color: #009900;">&#40;</span>strin<span style="color: #339933;">,</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span><span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>strin <span style="color: #339933;">!=</span><span style="color: #ff0000;">'<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Per uscire dal programma introducete una stringa vuota.<br />
Notare che la funzione gets non memorizza il carattere di newline, per cui ne aggiungiamo uno alla<br />
stringa letta da input, attraverso la funzione strcat, prima che tale stringa venga scritta nel file fpunt.<br />
La funzione rewind()<br />
La rewind() ripristina l’indicatore di posizione del file specificato ‘cursore’. Ossia il file e’ come se<br />
venisse ravvolto con la rewind().<br />
Il prototipo di tale funzione e’:<br />
void rewind (FILE *fpunt);<br />
fpunt e’ un puntatore ad un file.<br />
Le funzioni di lettura e scrittura formattata<br />
Sono la fprintf() e la fscanf() analoghe alla printf e scanf, soltanto che accettano un argomento in piu’,<br />
cioe’ il file dove scrivere o da cui leggere.<br />
I prototipi sono rispettivamente:<br />
int fprintf(FILE *fpunt, const char *stringa_formato, &lt;argomenti&gt;);<br />
la quale stampa nel file fpunt secondo le specifiche della stringa formato;<br />
e la<br />
int fscanf (FILE *fpunt, const char * stringa_formato, &lt;argomenti&gt;);<br />
la fscanf legge dal file fpunt i dati specificati nella stringa_formato.<br />
Cenni sui file ad accesso casuale<br />
I record di un file creati con l’output formattato della funzione fprintf non avranno necessariamente la<br />
stessa lunghezza. Ogni record di un file ad accesso casuale puo’ essere acceduto direttamente avendo di<br />
norma la stessa lunghezza. Dal momento che in un file ad accesso casuale ogni record ha lunghezza<br />
fissa, la sua posizione all’interno del file puo’ essere calcolata con una funzione della chiave del record.<br />
Le funzioni di lettura e scrittura per blocchi<br />
Attraverso le funzioni fread() ed fwrite() si possono leggere e scrivere rispettivamente interi blocchi di<br />
byte da un file.<br />
I loro prototipi sono:</p>
<p>size_t fread(void *buffer, size_t num_byte, size_t contatore, FILE *fpunt);<br />
size_t fwrite(void *buffer, size_t num_byte, size_t contatore, FILE *fpunt);</p>
<p>nella fread buffer e’ l’indirizzo di una locazione di memoria destinata a ricevere i dati letti dal file<br />
fpunt. Con essa si leggono dal file fpunt un blocco di contatore dati con ciascun dato avente dimensione<br />
num_byte. La fread restituisce il numero di elementi letti con successo.<br />
Le funzioni fread ed fwrite sono in grado di leggere e scrivere su disco interi vettori di dati.<br />
Il terzo argomento delle funzioni e’ il numero degli elementi del vettore che dovranno essere letti/scritti<br />
dal/sul disco.<br />
Vediamo adesso un programma che se il file viene aperto in modo binario scrive un double un int e un<br />
long in un file di nome fle_test e li rilegge:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
 <span style="color: #339933;">#include&lt;stdlib.h&gt;</span>
 <span style="color: #993333;">int</span> main <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 FILE <span style="color: #339933;">*</span>fpunt<span style="color: #339933;">;</span>
 <span style="color: #993333;">double</span> d<span style="color: #339933;">=</span><span style="color:#800080;">11.23</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">101</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">long</span> l<span style="color: #339933;">=</span><span style="color: #0000dd;">113023L</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>fpunt<span style="color: #339933;">=</span>fopen<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;file_test&quot;</span><span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;wb+&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">==</span>NULL<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;errore di apertura del file<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 fwrite<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>d<span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">double</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 fwrite<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>i<span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 fwrite<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>l<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">long</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 rewind<span style="color: #009900;">&#40;</span>fpunt<span style="color: #009900;">&#41;</span> <span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/*riposiziona il puntatore all'inizio del file*/</span>
 fread<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>d<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">double</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 fread<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>i<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 fread<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>l<span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">long</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%f %d %ld&quot;</span><span style="color: #339933;">,</span>d<span style="color: #339933;">,</span>i<span style="color: #339933;">,</span>l<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 fclose<span style="color: #009900;">&#40;</span>fpunt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Il linguaggio C consente le operazioni di lettura e scrittura ad accesso casuale usando la funzione<br />
fseek(), che ha il compito di posizionare il cursore del file.<br />
Il prototipo della fseek() e’:<br />
int fseek(FILE *fpunt, long num_byte, int origine);<br />
fpunt e’ il puntatore al file come viene restituito dalla funzione fopen();<br />
num_byte e’ il numero di byte di distanza tra l’origine e la nuova posizione (detto offset o<br />
scostamento); notare che in questo caso occorre usare l&#8217;operatore sizeof per accedere all&#8217;elemento<br />
desiderato; mentre origine e’ una delle seguenti macro definite da stdio.h :</p>
<ul>
<li>SEEK_SET: Inizio del file</li>
<li>SEEK_CUR: Posizione corrente</li>
<li>SEEK_END: Fine del file</li>
</ul>
<p>Per leggere l&#8217;ennesimo elemento del file fp, che supponiamo contenga elementi di tipo tipo_elementi,<br />
useremo:</p>
<p><em>fseek(fp,(n-1)*sizeof(tipo_elementi),SEEK_SET);<br />
fread(&amp;buffer,sizeof(tipo_elementi),1,fp);</em></p>
<h2>Esempio di programma per file binari</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include&lt;stdio.h&gt;</span>
 <span style="color: #339933;">#define N 15</span>
 <span style="color: #993333;">char</span> nome_file<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span><span style="color: #ff0000;">&quot;file_int.dat&quot;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> vector<span style="color: #009900;">&#91;</span>N<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">void</span> inserisci_in_array<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">void</span> crea_file<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">void</span> apri_file<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">char</span> car<span style="color: #339933;">;</span>
 inserisci_in_array<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 crea_file<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 apri_file<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 scanf<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>%c&quot;</span><span style="color: #339933;">,&amp;</span>car<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #993333;">void</span> inserisci_in_array<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>inserite gli %d elementi interi dell'array<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>N<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>N<span style="color: #339933;">;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span><span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d) &quot;</span><span style="color: #339933;">,</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 scanf<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d&quot;</span><span style="color: #339933;">,&amp;</span>vector<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #993333;">void</span> crea_file<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 FILE <span style="color: #339933;">*</span>fp<span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>fp<span style="color: #339933;">=</span>fopen<span style="color: #009900;">&#40;</span>nome_file<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;wb&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">!=</span>NULL<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
 fwrite<span style="color: #009900;">&#40;</span>vector<span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>N<span style="color: #339933;">,</span>fp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 fclose<span style="color: #009900;">&#40;</span>fp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;errore nell'apertura in scrittara del file %s &quot;</span><span style="color: #339933;">,</span>nome_file<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #993333;">void</span> apri_file<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 FILE <span style="color: #339933;">*</span>fp<span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>fp<span style="color: #339933;">=</span>fopen<span style="color: #009900;">&#40;</span>nome_file<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;rb&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">!=</span>NULL<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>fread<span style="color: #009900;">&#40;</span>vector<span style="color: #339933;">,</span>N<span style="color: #339933;">*</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>fp<span style="color: #009900;">&#41;</span><span style="color: #339933;">==</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span><span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>i<span style="color: #339933;">&lt;</span>N<span style="color: #339933;">;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
 <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot; %d) %d &quot;</span><span style="color: #339933;">,</span>i<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>vector<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 fclose<span style="color: #009900;">&#40;</span>fp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;errore nell'apertura del file %s in lettura&quot;</span><span style="color: #339933;">,</span>nome_file<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.fireteam.it/2009/07/gestione-dei-file-nel-linguaggio-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging con GNU GDB &#8211; Introduzione</title>
		<link>http://www.fireteam.it/2009/06/debugging-con-gnu-gdb-introduzione/</link>
		<comments>http://www.fireteam.it/2009/06/debugging-con-gnu-gdb-introduzione/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 08:18:14 +0000</pubDate>
		<dc:creator>saverio</dc:creator>
				<category><![CDATA[Programmazione C]]></category>
		<category><![CDATA[debugger]]></category>
		<category><![CDATA[gdb]]></category>

		<guid isPermaLink="false">http://www.fireteam.it/?p=166</guid>
		<description><![CDATA[Introduzione al debugging con Gnu Debugger (gdb) in ambiente Linux.]]></description>
			<content:encoded><![CDATA[<p>GNU debugger (talvolta chiamato semplicemente GDB) è il nome di un programma libero sviluppato da GNU. È il debugger predefinito del software GNU, gira su molte piattaforme (tra cui i sistemi Unix-like e Microsoft Windows) ed è capace di analizzare numerosi linguaggi di programmazione, tra cui Ada, C, C++ e Fortran.</p>
<p>GDB (ovvero GNU DeBugger) è molto più di un semplice debugger: è un vero e proprio program execution path analysis tool.<br />
Invocando il comando “gdb &#8211;help” avremo:</p>
<pre class="shell">This is the GNU debugger.  Usage:

    gdb [options] [executable-file [core-file or process-id]]
    gdb [options] --args executable-file [inferior-arguments ...]

Options:

  --args             Arguments after executable-file are passed to inferior
  --[no]async        Enable (disable) asynchronous version of CLI
  -b BAUDRATE        Set serial port baud rate used for remote debugging.
  --batch            Exit after processing options.
  --cd=DIR           Change current directory to DIR.
  --command=FILE     Execute GDB commands from FILE.
  --core=COREFILE    Analyze the core dump COREFILE.
  --pid=PID          Attach to running process PID.
  --dbx              DBX compatibility mode.
  --directory=DIR    Search for source files in DIR.
  --epoch            Output information used by epoch emacs-GDB interface.
  --exec=EXECFILE    Use EXECFILE as the executable.
  --fullname         Output information used by emacs-GDB interface.
  --help             Print this message.
  --interpreter=INTERP
                     Select a specific interpreter / user interface
  --mapped           Use mapped symbol files if supported on this system.
  --nw               Do not use a window interface.
  --nx               Do not read .gdbinit file.
  --quiet            Do not print version number on startup.
  --readnow          Fully read symbol files on first access.
  --se=FILE          Use FILE as symbol file and executable file.
  --symbols=SYMFILE  Read symbols from SYMFILE.
  --tty=TTY          Use TTY for input/output by the program being debugged.
  --version          Print version information and then exit.
  -w                 Use a window interface.
  --write            Set writing into executable and core files.
  --xdb              XDB compatibility mode.</pre>
<p><span id="more-166"></span></p>
<p>Bhè… ci sono molte opzione, come la maggior parte dei programmi <img src='http://www.fireteam.it/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' />  . in questa guida ci limiteremo a chiamare gdb passandoci semplicente il nome dell’eseguibile da analizzare.<br />
Facciamo subito il solito primo esempio: hello.c.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include </span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Hello World<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Se vogliamo analizzare questo programma dobbiamo compilarlo con l’opzione “-g” del compilatore gcc; in questo modo l’eseguibile conterrà delle informazioni utili al debugger per analizzare il programma. Compiliamo…</p>
<pre class="shell">emac:~/temp ferrara$ gcc -g -o helloworld hello.c
emac:~/temp ferrara$ ls -l
total 32
-rw-r--r--  1 ferrara  ferrara     72 19 Nov 22:41 hello.c
-rwxr-xr-x  1 ferrara  ferrara  11764 19 Nov 22:45 helloworld</pre>
<p>Adesso abbiamo il nostro eseguibile chiamato “helloword” compilato per essere esaminato con gdb. Non ci resta che lanciare il comando:</p>
<pre class="shell">emac:~/temp ferrara$ gdb helloworld
GNU gdb 5.3-20030128 (Apple version gdb-309) (Thu Dec  4 15:41:30 GMT 2003)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "powerpc-apple-darwin".
Reading symbols for shared libraries .. done
(gdb) <strong>&lt;-- Prompt di gdb</strong></pre>
<p>Gdb ha caricato il nostro eseguibile e ci ha presentato il suo prompt (gdb). Adesso abbiamo svariati comandi a nostra disposizione! Esaminiamo il più semplice: list. Esso, seguito dal nome della funzione o del numero di linea, ci presenta a video il sorgente:</p>
<pre class="shell">(gdb) list main <strong>&lt; -- Comando dato al prompt di gdb</strong>
1       #include
2
3       int main()
4       {
5               printf("Hello World\n");
6               exit(0);
7       }
8</pre>
<p>Per maggiori informazioni basta digitare il comando “help list” al prompt di gdb per avere maggiori informazioni su questo comando. Ma come fa gdb a sapere il codice del programma helloworld se noi abbiamo fassato come argomento solo l’eseguibile? Questa informazione è stata registrata nell’eseguibile grazie all’opzione –g del compilatore <img src='http://www.fireteam.it/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .<br />
Ora con il comando run facciamo girare il programma all’interno di gdb:</p>
<pre class="shell">(gdb) run &amp;tab; &lt; -- Comando dato al prompt di gdb
Starting program: /Users/ferrara/temp/helloworld
Reading symbols for shared libraries . done
Hello World &amp;tab; &lt;-- Output del pogramma

Program exited normally.</pre>
<p>Come si poteva immaginare non ci sono errori. Alla fine dell’esecuzione gdb ci ripresenta il suo prompt e possiamo continuare a dargli altri comandi.<br />
Adesso proveremo a disassemblare il codice di helloworld con il comando disass:</p>
<pre class="shell">(gdb) disass main <strong>&lt; -- Comando dato al prompt di gdb</strong>
Dump of assembler code for function main:
0x00001da4 :    mflr    r0
0x00001da8 :    stmw    r30,-8(r1)
0x00001dac :    stw     r0,8(r1)
0x00001db0 :   stwu    r1,-80(r1)
0x00001db4 :   mr      r30,r1
0x00001db8 :   bcl-    20,4*cr7+so,0x1dbc
0x00001dbc :   mflr    r31
0x00001dc0 :   addis   r3,r31,0
0x00001dc4 :   addi    r3,r3,564
0x00001dc8 :   bl      0x1f34
0x00001dcc :   li      r3,0
0x00001dd0 :   bl      0x1dd4
End of assembler dump.</pre>
<p>Questa funzione di gdb delizierà gli smanettoni, ma non approfondiremo questo argomento.<br />
Per uscire dal gdb e quindi tornare al prompt della nostra shell bastera digitare il comando quit o semplicemente q.</p>
<h2>Primo esempio di debugging</h2>
<p>Esaminiamo il seguente programma (segmentation_fault.c):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include</span>
<span style="color: #339933;">#include </span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>buf<span style="color: #339933;">;</span>
&nbsp;
        strcpy<span style="color: #009900;">&#40;</span>buf<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;HelloWorld&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> buf<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Questo programma stampa a video “HelloWorld”. Ma eseguendolo abbiamo un errore:</p>
<pre class="shell">emac:~/temp ferrara$ gcc -g -o sfault segmentation_fault.c
emac:~/temp ferrara$ ./sfault
Bus error</pre>
<p>Dove abbiamo sbagliato? Lanciamo gdb e diamo il comando run per avviare il programma:</p>
<pre class="shell">emac:~/temp ferrara$ gdb sfault <strong>&lt; -- Comando dato alla shell per avviare gdb</strong>
GNU gdb 5.3-20030128 (Apple version gdb-309) (Thu Dec  4 15:41:30 GMT 2003)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "powerpc-apple-darwin".
Reading symbols for shared libraries .. done
(gdb) run &amp;tab; &lt;-- Comando dato al prompt di gdb
Starting program: /Users/ferrara/temp/sfault
Reading symbols for shared libraries . done

Program received signal EXC_BAD_ACCESS, Could not access memory. <strong>&lt;-- Trovato un errore</strong>
0x90007680 in strcpy () <strong>&lt;-- La funzione dove si blocca il programma è strcpy</strong>
(gdb) <strong>&lt;-- Prompt di gdb per eventuali altri comandi</strong></pre>
<p>Questa è un informazione utilissima, ma si può avere di più. Siccome è difficile pensare che ci sia un bug nelle glibc (cioè dove è implementata la funzione strcpy()) proviamo a pensare che abbiamo passato alla funzione i parametri sbagliati, quindi inseriremo un breakpoint alla riga 8 e mentre il programma rimane bloccato aspettando il comando step per superare il breakpoint gli faremo stampare la variabile buf e il suo contenuto per verificarlo:</p>
<pre class="shell">(gdb) list <strong>&lt;-- Chiedo il listato del sorgente</strong>
1       #include
2       #include
3
4       int main()
5       {
6               char *buf;
7               long i;
8
9               strcpy(buf,"HelloWorld");
10
(gdb) b 8 <strong>&lt;-- Inserisco un breakpoint alla riga 8</strong>
Breakpoint 1 at 0x1d8c: file segmentatio_fault.c, line 8.
(gdb) run <strong>&lt;-- Avvio il programma</strong>
The program being debugged has been started already.
Start it from the beginning? (y or n) y <strong>&lt;-- Chiedo di ricominciare da capo</strong>
Starting program: /Users/ferrara/temp/sfault 

Breakpoint 1, main () at segmentatio_fault.c:9
9               strcpy(buf,"HelloWorld"); <strong>&lt;-- Si è fermato prima di eseguire la riga 9</strong>
(gdb) p buf <strong>&lt;-- Stampo la variabile buf</strong>
$1 = 0x0
(gdb) p *buf <strong>&lt;-- Stampo il contenuto di buf</strong>
Cannot access memory at address 0x0 <strong>&lt;-- Questo è il notro errore</strong>
(gdb) bt <strong>&lt;-- Stampo lo stack del programma alla riga 8</strong>
#0  main () at segmentatio_fault.c:9
(gdb) step  <strong>&lt;-- Continuiamo l’esecuzione del programma</strong>

Program received signal EXC_BAD_ACCESS, Could not access memory.
0x90007680 in strcpy ()
(gdb) bt <strong>&lt;-- Stampo lo stack dopo il blocco del programma</strong>
#0  0x90007680 in strcpy () <strong>&lt;-- Il programma si è bloccato in questa punto</strong>
#1  0x00001d9c in main () at segmentatio_fault.c:9
(gdb) clear 8 <strong>&lt;-- Cancello il breakpoint alla riga 8</strong>
Deleted breakpoint 1
(gdb) q <strong>&lt;-- Esco da gdb perché ho tutte le informazioni che mi servono</strong>
The program is running.  Exit anyway? (y or n) y <strong>&lt;-- Confermo</strong>
emac:~/temp ferrara$ <strong>&lt;-- Prompt di shell</strong></pre>
<p>Il codice di questo programma era molto semplice, e il bug si poteva trovare anche solo leggendo il codice sorgente. Intanto abbiamo imparato l’utilizzo base dei seguenti comandi:</p>
<table border="0">
<tbody>
<tr>
<td>b</td>
<td>(breakpoint) &#8211; Inserisce un breakpoint.</td>
</tr>
<tr>
<td>step</td>
<td>Supera il breakpoint in cui si è fermato e raggiunge il prossimo breakpoint oppure a fine del programma.</td>
</tr>
<tr>
<td>clear</td>
<td>Cancella un breakpoint.</td>
</tr>
<tr>
<td>run</td>
<td>Esegue il programma che stiamo esaminando e lo fa ripartire se si blocca o finisce.</td>
</tr>
<tr>
<td>p</td>
<td>(print) – Stampa a video il contenuto di una variabile (puntatore, struttura, o altro).</td>
</tr>
<tr>
<td>bt</td>
<td>(backtrace) – Stampa il backtrace dello stack corrente.</td>
</tr>
<tr>
<td>list</td>
<td>Stampa il codice sorgente del programma. E’ un modo per sapere in quale linea inserire il breakpoint.</td>
</tr>
<tr>
<td>q</td>
<td>(quit) – Uscita da gdb.</td>
</tr>
</tbody>
</table>
<h2>Programmi che richiedono parametri</h2>
<p>Per analizzare dei programmi che richiedono parametri come questo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include </span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> i<span style="color: #339933;">,</span>a<span style="color: #339933;">;</span>
	<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>car<span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> ALLOCATO<span style="color: #339933;">,</span>SCRITTI<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>argc <span style="color: #339933;">!=</span> <span style="color: #0000dd;">3</span><span style="color: #009900;">&#41;</span>
		<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;usa: %s  <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	ALLOCATO <span style="color: #339933;">=</span> atoi<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	SCRITTI <span style="color: #339933;">=</span> atoi<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	car <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> malloc<span style="color: #009900;">&#40;</span>ALLOCATO<span style="color: #339933;">*</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>a<span style="color: #339933;">=</span><span style="color: #ff0000;">'a'</span> <span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> SCRITTI <span style="color: #339933;">;</span> i<span style="color: #339933;">++,</span>a<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
		car<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>a<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>car<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Basta chiamare gdb come abbiamo fatto finora e passare gli argomenti assieme al comando run:</p>
<pre class="shell">(gdb) run 5 5
Starting program: /Users/ferrara/temp/serio 5 5
Reading symbols for shared libraries . done
abcde

Program exited normally.
(gdb)</pre>
<p>Passando come secondo argomento un numero molto grande rispetto al primo si ha un vero e proprio segmentation fault:</p>
<pre class="shell">(gdb) run 5 99999999
Starting program: /Users/ferrara/temp/serio 5 99999999

Program received signal EXC_BAD_ACCESS, Could not access memory.
0x00001d40 in main (argc=3, argv=0xbffffce8) at serio.c:18
18                      car[i]=a;
(gdb)</pre>
<p>Come mai accade questo? Adesso avete gli strumenti necessari per procedere da soli… buon divertimento con gdb!</p>
<h2>Conclusioni</h2>
<p>Questo documento è da considerarsi una semplicissima introduzione, giusto quel che basta per cominciare ad usare il manuale di gdb senza perdersi tra le tantissime opzioni.<br />
Per ulteriori informazioni digitare il comando “man gdb” dal prompt di shell oppure “help ” dal prompt di gdb.</p>
<p>Per ci si scoccia di usare un debugger a linea di comando può trovare delle front end per gdb come xxgdb.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fireteam.it/2009/06/debugging-con-gnu-gdb-introduzione/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Split di stringhe in C</title>
		<link>http://www.fireteam.it/2009/06/split-di-stringhe-in-c/</link>
		<comments>http://www.fireteam.it/2009/06/split-di-stringhe-in-c/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 12:23:52 +0000</pubDate>
		<dc:creator>ivan</dc:creator>
				<category><![CDATA[Programmazione C]]></category>
		<category><![CDATA[linguaggio c]]></category>
		<category><![CDATA[split]]></category>
		<category><![CDATA[stringhe]]></category>

		<guid isPermaLink="false">http://www.fireteam.it/?p=106</guid>
		<description><![CDATA[Un tutorial che insegna a creare una funzione di split per le stringhe, le stringhe sono dinamicamente allocate in un array.]]></description>
			<content:encoded><![CDATA[<p>Salve a tutti, oggi cercherò di spiegare come creare una funzione di split per le vostre stringhe in C. Tempo fa cercai su internet qualche fonte esaustiva ma non ho trovato nulla di buono.<br />
Premetto che i requisiti affinchè capiate il tutorial è una buona conoscenza di C e dei puntatori.(Non è mio compito scoraggiare il lettore, ma l&#8217;autore fino a dicembre non sapeva nemmeno come si faceva un allocazione dinamica, con un pò di impegno, chiunque può imparare in tempi brevi!).</p>
<p>Finite queste quattro chiacchiere, presenterò nel tutorial 2 files, un file conterrà tutte le funzioni,  l&#8217;altro invece sarà un programmino di esempio che ne illustrerà l&#8217;uso. Cominciamo con il primo file, lo chiameremo split.h, qui ci vanno le nostre funzioni, #define vari, includes&#8230;</p>
<p><span id="more-106"></span></p>
<h3>file split.h</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;string.h&gt;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;malloc.h&gt;</span>
<span style="color: #339933;">#include &lt;memory.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define KB 1024</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// funzioni sulla memoria delle stringhe</span>
&nbsp;
<span style="color: #993333;">int</span> getAllocatedElements<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">**</span>array<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">return</span> _msize<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> freeArray<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">**</span>array<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> prompt<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>array<span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// altrimenti riazzero tutto gia messo</span>
<span style="color: #993333;">int</span> dim<span style="color: #339933;">=</span>getAllocatedElements<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> bytesFree<span style="color: #339933;">=</span>dim<span style="color: #339933;">*</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>prompt<span style="color: #009900;">&#41;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>dim<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
       <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>prompt<span style="color: #009900;">&#41;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Libero la stringa allocata: %s(%d bytes allocati)<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>_msize<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
       bytesFree<span style="color: #339933;">+=</span>_msize<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       free<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>prompt<span style="color: #009900;">&#41;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d Indirizzi da liberare(%d bytes)<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>dim<span style="color: #339933;">,</span>dim<span style="color: #339933;">*</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
free<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
<span style="color: #b1b100;">return</span> bytesFree<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Funzioni di stringhe</span>
&nbsp;
<span style="color: #993333;">char</span><span style="color: #339933;">*</span> Reverse<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span> str<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> ptrstr<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">int</span> l<span style="color: #339933;">=</span>strlen<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> j<span style="color: #339933;">=</span>l<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">,</span>j<span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>l<span style="color: #339933;">,</span> j<span style="color: #339933;">&gt;=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++,</span>j<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span> ptrstr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>str<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
ptrstr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #ff0000;">'<span style="color: #006699; font-weight: bold;">\0</span>'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">return</span> <span style="color: #339933;">&amp;</span>ptrstr<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">char</span><span style="color: #339933;">*</span> Replace<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> src<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> newc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> str<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">int</span> l<span style="color: #339933;">=</span>strlen<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>l<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">==</span>src<span style="color: #009900;">&#41;</span> str<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>newc<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">return</span> <span style="color: #339933;">&amp;</span>str<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">char</span><span style="color: #339933;">*</span> ReplaceFirst<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> src<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> newc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> str<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">int</span> l<span style="color: #339933;">=</span>strlen<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>l<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">==</span>src<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> str<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>newc<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">return</span> <span style="color: #339933;">&amp;</span>str<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> Count<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> c<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>str<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">int</span> n<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span> strlen<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
       <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">==</span>c<span style="color: #009900;">&#41;</span> n<span style="color: #339933;">++;</span>
&nbsp;
<span style="color: #b1b100;">return</span> n<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> CountStrings<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">**</span>array<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">int</span> dim<span style="color: #339933;">=</span>getAllocatedElements<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> n<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>dim<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
      <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>strlen<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&gt;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> n<span style="color: #339933;">++;</span>
<span style="color: #b1b100;">return</span> n<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> print<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">**</span>array<span style="color: #339933;">,</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> max<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>max<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
       <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> printAll<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">**</span>array<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> print<span style="color: #009900;">&#40;</span>array<span style="color: #339933;">,</span> getAllocatedElements<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// -----------------------------------------------------------------------------</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// SPLIT 2.0</span>
<span style="color: #993333;">char</span><span style="color: #339933;">**</span> Split<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>str<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> c<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>array<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>array<span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> NULL<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// altrimenti riazzero tutto gia messo</span>
<span style="color: #993333;">int</span> dim<span style="color: #339933;">=</span>getAllocatedElements<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> memtoalloc<span style="color: #339933;">=</span>Count<span style="color: #009900;">&#40;</span>c<span style="color: #339933;">,</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span>dim<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>memtoalloc<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
array<span style="color: #339933;">=</span>realloc<span style="color: #009900;">&#40;</span>array<span style="color: #339933;">,</span> _msize<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span>memtoalloc<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>array<span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> NULL<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> z<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>z<span style="color: #339933;">;</span> z<span style="color: #339933;">&lt;</span>dim<span style="color: #339933;">;</span> z<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
       free<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#91;</span>z<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
       <span style="color: #993333;">char</span> buffer<span style="color: #009900;">&#91;</span>KB<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
       <span style="color: #993333;">int</span> n<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// conto tokens</span>
&nbsp;
       <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&lt;</span> strlen<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
       <span style="color: #009900;">&#123;</span>
               <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">!=</span>c<span style="color: #009900;">&#41;</span>
               <span style="color: #009900;">&#123;</span>
               buffer<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>str<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
               j<span style="color: #339933;">++;</span>
               <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
               buffer<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #ff0000;">'<span style="color: #006699; font-weight: bold;">\0</span>'</span><span style="color: #339933;">;</span>
&nbsp;
               array<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>calloc<span style="color: #009900;">&#40;</span> strlen<span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// alloco un nuovo indirizzo per contenere la stringa stessa</span>
               <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>array<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> NULL<span style="color: #339933;">;</span>
&nbsp;
               strcpy<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
               j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>  
&nbsp;
               n<span style="color: #339933;">++;</span> <span style="color: #666666; font-style: italic;">// incremento il n di tokens</span>
               <span style="color: #009900;">&#125;</span>
       i<span style="color: #339933;">++;</span>
       <span style="color: #009900;">&#125;</span>
&nbsp;
       <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>strlen<span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">&gt;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
       <span style="color: #009900;">&#123;</span>
       buffer<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #ff0000;">'<span style="color: #006699; font-weight: bold;">\0</span>'</span><span style="color: #339933;">;</span>
               array<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>calloc<span style="color: #009900;">&#40;</span> strlen<span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// alloco un nuovo indirizzo per contenere la stringa stessa</span>
               <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>array<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> NULL<span style="color: #339933;">;</span>
&nbsp;
               strcpy<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
               j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
               n<span style="color: #339933;">++;</span> <span style="color: #666666; font-style: italic;">// incremento il n di tokens</span>
       <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">return</span> array<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>E&#8217; ora di utilizzare le funzioni create, passiamo al main:</p>
<h3>file main.c</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;strings.h&quot;</span>
<span style="color: #666666; font-style: italic;">// Usare split 2.0</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">int</span> toks<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// numero di pezzi</span>
&nbsp;
<span style="color: #993333;">char</span> <span style="color: #339933;">**</span>array<span style="color: #339933;">=</span>calloc<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// allocazione di una memoria di base, successivamente verrà adattata</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Memoria insufficiente&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #666666; font-style: italic;">// un computer degli anni 30 non potra allocare tanta memoria, se non esiste il puntatore termina subito</span>
&nbsp;
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>str1<span style="color: #339933;">=</span><span style="color: #ff0000;">&quot;Il mio cane e molto cattivo e bambino&quot;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>str2<span style="color: #339933;">=</span><span style="color: #ff0000;">&quot;uno due#tre quattro#cinque sei#sette otto#nove dieci&quot;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// le stringhe di esempio</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Prima del primo split, gli indirizzi allocati occupano %d bytes&quot;</span><span style="color: #339933;">,</span>_msize<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>Split(separatore: spazio) della stringa:<span style="color: #000099; font-weight: bold;">\n</span>'%s'<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>str1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Puntatore all'array: %p<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
array<span style="color: #339933;">=</span>Split<span style="color: #009900;">&#40;</span>str1<span style="color: #339933;">,</span><span style="color: #ff0000;">' '</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Nuovo puntatore all'array: %p<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Numero di stringhe estratte: %d<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>CountStrings<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
printAll<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>Dopo il primo split, gli indirizzi allocati occupano %d bytes&quot;</span><span style="color: #339933;">,</span>_msize<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Un altro split, riutilizzando la memoria precedente, e rimodellandola dinamicamente</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>Split(separatore: #) della stringa:<span style="color: #000099; font-weight: bold;">\n</span>'%s'<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>str2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Puntatore attuale all'array: %p<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
array<span style="color: #339933;">=</span>Split<span style="color: #009900;">&#40;</span>str2<span style="color: #339933;">,</span><span style="color: #ff0000;">'#'</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Puntatore dopo l'ultima modifica: %p<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Numero di stringhe estratte: %d<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>CountStrings<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
printAll<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>Dopo il secondo split, gli indirizzi allocati occupano %d bytes&quot;</span><span style="color: #339933;">,</span>_msize<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>Memoria liberata: %d bytes<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> freeArray<span style="color: #009900;">&#40;</span>array<span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #808080; font-style: italic;">/*
 necessaria, non usare free(liberera solo gli indirizzi),
 ricorda di non liberare mai la memoria 2 volte,
 liberala solo quando non ti serve piu
*/</span>
&nbsp;
system<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;pause&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// in modalità windows, dove lavoreremo noi, serve ad una pausa</span>
<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Il tutorial è finito, spero di aver fatto contento qualcuno, segnalatemi errori o suggerimenti, grazie per la lettura al prossimo tutorial!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fireteam.it/2009/06/split-di-stringhe-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
