Your life is ending one minute at a time. La tua vita è che si conclude un minuto alla volta.If you were to die tomorrow, what would you do today? Se si dovesse morire domani, cosa farebbe oggi?
C Programming :: A Basic Tutorial ::C Programming:: Un tutorial di base::
Published by: dEmOn , on 2007-09-08 10:21:54 Pubblicato da: Demon, il 2007-09-08 10:21:54
This is my first article here..^^ Questo è il mio primo articolo qui .. ^ ^
well.. bene ..
i didn't "directly" wrote this tutorial here... Io non "direttamente" ha scritto questo tutorial qui ...
This is originally from my site: http://www.cprogrammingdock.serverspeople.net/ Questo è originariamente dal mio sito: http://www.cprogrammingdock.serverspeople.net/ which i wrote few months ago..^^ che ho scritto qualche mese fa .. ^ ^
and thought this maybe useful to those who haven't yet visited the site.. e questo pensiero forse utile a coloro che non hanno ancora visitato il sito ..
So here we are :D Quindi, qui ci sono: D
+++++++++++++++++++++++++++++++++ C Programming C Programming +++++++++++++++++++++++++++++++++
What is C programming? Qual è la programmazione C?The C Programming Language is a structured, modular, compiled, general purpose language Traditionally used for system programming. The C Programming Language è una banca dati strutturata, modulare, compilato, per uso generale lingua Tradizionalmente usato per il sistema di programmazione.It is portable, so you can easily transfer application programs written in C from one system from one another. E 'portatile, in modo da poter trasferire facilmente alle applicazioni scritte in C da un sistema da un altro.You can use C for almost any programming task, anywhere. È possibile utilizzare C per quasi qualsiasi compito di programmazione, ovunque.
C allows the most precise control of input and output. C consente la più preciso controllo di ingresso e di uscita.This can result in short efficient programs, where the programmer has made wise use of C's range of powerful operators. Questo può tradursi in programmi di breve efficiente, in cui il programmatore ha fatto una saggia utilizzazione di C della gamma di potenti operatori.It also allows the programmer to produce programs which are impossible to understand. Esso consente inoltre il programmatore per produrre programmi che sono impossibili da capire.
Learning in C can result for better understanding of other languages such as C++, which is the superset of C, and many others, they almost share the same format. Imparare in C può comportare per una migliore comprensione di altre lingue come il C + +, che è il superset di C, e molti altri, quasi che condividono lo stesso formato.If you were familiar with C, you can have knowledge support to learn other Programming Languages. Se sono stati familiarità con il linguaggio C, è possibile essere a conoscenza di sostegno per imparare altri linguaggi di programmazione.
++++++++++++++++++++++++++++++++++++ Your First Program in C Il vostro primo programma in C ++++++++++++++++++++++++++++++++++++
This section of this tutorial will teach you how to write a program in C. Questa sezione di questo tutorial vi insegnerà come scrivere un programma in C.
Here is the most popular program, "Hello World!" Qui è il programma più popolare, "Ciao Mondo!"
Hello World! Ciao a tutti!
Write this on your editor, Scrivere questo sul tuo editor,
Save this as Hello.c, .c extension means that the file is a C source code. Salva come hello.c,. C estensione significa che il file è un codice sorgente C.Now, compile this code using your compiler, then execute/run the code. Ora, compilare il codice utilizzando il compilatore, quindi eseguire / eseguire il codice.If you are using Turbo C, you saw the screen flash, and nothing happened, press alt + f5 to view your work. Se si sta usando Turbo C, avete visto la schermata di flash, e non è accaduto nulla, premere Alt + F5 per visualizzare il tuo lavoro.
Lets talk about our program, in our program, we output the string "Hello World!", for we to do that , we made use of a function, the function printf, we will talk more of this later. Consente di parlare del nostro programma, nel nostro programma, abbiamo uscita la stringa "Ciao Mondo!", Per fare questo, abbiamo fatto uso di una funzione, la funzione printf, ci occuperemo di questo più tardi.
We started typing "#include", this is a preprocessor, along that we typed <stdio.h> this means that we included the header file stdio.h, this file contains the functions that we will use, one of the function we used is printf. Abbiamo iniziato a digitare "# include", questo è un preprocessore, che insieme abbiamo digitato <stdio.h> questo significa che abbiamo inserito il file header stdio.h, questo file contiene le funzioni che useremo, una delle funzioni che abbiamo usato è printf.
Next, we typed main(), this is the main part or the body of our program, under main are statements enclosed with brackets ( "{ }"). Quindi, abbiamo digitato main (), questa è la parte principale o il corpo del nostro programma, in virtù principali sono stati chiusi con tra parentesi ( "()").In our main program we typed, Nel nostro programma principale abbiamo digitato,
And we used printf. E abbiamo usato printf.printf outputs data into the screen, as we have done, we made printf output Hello World! printf uscite di dati in schermo, come abbiamo fatto, abbiamo fatto printf uscita Ciao Mondo!on the screen. sullo schermo.In the code, Hello World! Nel codice, Ciao Mondo!is followed by "n", this is an escape sequence, this tells the compiler to move the cursor to the next line. è seguita da "n", questa è una sequenza di escape, questo dice il compilatore per spostare il cursore alla riga successiva.
There are many kinds of escape sequences, here are the mostly used: Ci sono molti tipi di sequenze di escape, qui sono i più utilizzati:
\n - newline \ n - a capo
\t - tab \ t - scheda
\b - backspace \ b - backspace
\xhhh - insert the character represented by ASCII code hhh, where hhh is equal to 1 to 3 hexadecimal digits \ xhhh - inserire il carattere rappresentato dal codice ASCII hhh, dove HHH è pari a 1 a 3 cifre esadecimali
You may have noticed, the statement ends in semicolon ";", this tells the compiler that it is the end of a sentence. Forse avrai già notato, la dichiarazione termina in punto e virgola ";", questo dice il compilatore che è la fine di una frase.If you forgot to put a semicolon after each statements, you will receive an error that tell that a semicolon is missing in the particular statement. Se hai dimenticato di mettere un punto e virgola dopo ogni dichiarazioni, si riceverà un messaggio di errore che dire che è un punto e virgola mancante in particolare la dichiarazione.
+++++++++++++++++++++++++++++++ Math in C Math in C +++++++++++++++++++++++++++++++
Now that we know how to output. Ora che sappiamo come output.We can now go on and lets talk about Math in C and Inputs. Ora possiamo andare avanti e consente di parlare di matematica in C e ingressi.
Modify Hello.c, edit it like this. Modifica hello.c, modificarlo come questo. CODE : CODICE:
#include <stdio.h># include <stdio.h>
main()main () {( int a,b,sum;int a, b, somma;
printf("Enter two numbers: ");printf ( "Inserisci due numeri:"); scanf("%d %d", &a,&b);scanf ( "% d% d", & a, & b); sum = a + b;somma = a + b; printf("\nThe sum is %d", sum);printf ( "\ nIl messaggio somma è% d", somma); })
Save this as sum.c Salva come sum.c
Let us now analyze. Cerchiamo ora di analizzare.Under the main program, there are several changes, Nell'ambito del programma principale, ci sono diversi cambiamenti,
CODE : CODICE:
int a,b,sum;int a, b, somma;
The statement above means that we declared 3 variables under 1 data type "int", the variables were, a, b and sum. La dichiarazione di cui sopra significa che abbiamo dichiarato 3 variabili di cui al punto 1 il tipo di dati "int", le variabili sono state, A, B e somma. Data Types Tipi di dati
There are many data types in C, here are the four basic types: Ci sono molti tipi di dati in C, qui sono le quattro tipologie fondamentali:
Integers - numbers you learned to count. Interi - numeri che hanno imparato a contare.
Floating Point Numbers - have fractional portions and exponents, also known as real numbers. I numeri in virgola mobile - hanno frazionario porzioni ed esponenti, anche noto come numeri reali.
Text - made up of single characters and strings. Testo - fatta di singoli caratteri e stringhe.
Pointers - holds the address of variables. Puntatori - detiene l'indirizzo di variabili.Does not hold data. Non sia in possesso di dati. Format Specifications Formato Specifiche
Another statements that are new are, Un altro sono le dichiarazioni che sono nuovi,
CODE : CODICE:
scanf("%d %d", &a,&b);scanf ( "% d% d", & a, & b); sum = a + b;somma = a + b; printf("nThe sum is %d", sum);printf ( "nIl messaggio somma è% d", somma);
Now we used the scanf function. Ora abbiamo utilizzato la funzione scanf.scanf lets the user to input data during runtime. scanf consente all'utente di inserire i dati durante il runtime.We made use of "%d".%d is one kind of format command called a format specification. Abbiamo fatto uso di "% d".% D è un tipo di formato di comando chiamato un formato disciplinare.scanf says that we must input 2 integers seperated by a space. scanf dice che dobbiamo ingresso 2 interi separati da uno spazio.All format specifications starts with a percent sign "%" and usually followed by a single letter, indicating the data type to be inserted. Tutte le specifiche di formato inizia con un segno di percentuale "%" e di solito seguita da una sola lettera, indicando il tipo di dati da inserire.%d is the format specification which means integer. % d è il formato che significa intero.So, you can only input numbers from -32768 to 32767. Quindi, si può solo immettere i numeri da -32.768 a 32.767.
Here are other examples of format specifications and the data type they specifies, Ecco altri esempi di formato e le specifiche del tipo di dati che specifica,
%u - unsigned integer - 0 to 65535 % u - unsigned intero - da 0 a 65535
%ld - long integer - - 2147483648 to 2147483647 % ld - lungo intero - - 2147483648 al 2147483647
%p - pointer value % p - puntatore valore
%f - floating point - 3.4-38 to 3.4+38 % f - in virgola mobile - 3.4-38 a 3.4 38
%e - float in exponential form % e - galleggiante in forma esponenziale
%c - character % c - carattere
%s - string % s - stringa
%x - integer in hexadecimal format % x - intero in formato esadecimale
In our program, after the format specification, we typrd &a,&b, this means that when the user inputs the first integer, it will be addressed to a, "&"is an address operator.Same as the second integer, when the user inputs the second integer, it will be addressed to b. Nel nostro programma, dopo il formato, abbiamo typrd & A, & b, questo significa che quando l'utente ingressi il primo numero intero, sarà indirizzata ad uno, "&" è un indirizzo operator.Same come il secondo numero intero, quando l'utente ingressi intero il secondo, sarà indirizzata al b.
The next statement is more like the operation of our program, it says that add a and b together and assign the answer to sum. L'ordine del giorno è più simile al funzionamento del nostro programma, si dice che aggiungere A e B insieme e assegnare la risposta alla somma."=" is an assignment operation, the operations usually take process on the rvalue(right value), and to be addressed to the lvalue(left value) by =. "=" È una operazione di assegnazione, le operazioni di solito prendono il processo rvalue (a destra valore), e di essere indirizzata al lvalue (a sinistra valore) da =.
in the last statement, we used printf again, and we again used format specification. in ultima dichiarazione, abbiamo utilizzato printf nuovamente, e abbiamo usato di nuovo formato.When we are using format specifications in output, we are referring to a variable which holds value and to be printed on the screen, for that, we must call the name of the variable after the string, like our example, Quando stiamo usando il formato specifiche della produzione, ci si riferisce a una variabile che detiene il valore e di essere stampato sullo schermo, per questo, dobbiamo chiedere il nome della variabile dopo la stringa, come il nostro esempio,
CODE : CODICE:
printf("nThe sum is %d", sum);printf ( "nIl messaggio somma è% d", somma);
This outputs the value of the variable sum. Questo uscite il valore della variabile somma.sum has a value of a + b. somma ha un valore di A + B.
Now you know how are these statements connected, pretty cool ha?! Ora sapete come sono collegati a tali dichiarazioni, ha pretty cool?! Arithmetic Operators Operatori aritmetici
Here are the commonly used operations in C, Qui ci sono le operazioni comunemente usate in C,
+ Addition + Aggiunta
- Subtraction - La sottrazione
* Multiplication * Moltiplicazione
/ Division / Divisione
% Modulus(Remainder) Modulo% (il resto)
++ Increment + + Incremento
-- Decrement - Decremento
You might be confused, in a++ and ++a, this is mostly confusing in operations. Potrebbe essere confuso, in un + + e + + uno, questo è in gran parte nelle operazioni di confusione.
Suppose there are two expressions, Supponiamo che vi sono due espressioni,
CODE : CODICE:
sum = a + b++;somma = a + b + +;
sum = a + ++b ;somma = a + b + +;
The first expression says, "Add a and b together, assign the result to sum, and increment b by one. The second says "Increment b by one, a and b together, and assign the result to sum.Get it? La prima espressione dice, "Aggiungi A e B insieme, assegnare il risultato a somma, e incremento b per uno. Il secondo dice:" Incremento b per uno, A e B insieme, e assegnare il risultato sum.Get essa?
There are two other types of operations that we haven't discussed yet, these are logical and relational operators. Ci sono altri due tipi di operazioni che non abbiamo ancora discusso, si tratta di logica e relazionale degli operatori. Relational Operations Operazioni relazionali
Relational operations allow you to compare two values, yielding the result based on whether the comparison is true or false. Relazionale operazioni permettono di confrontare due valori, ottenendo il risultato basato su se il confronto è vero o falso.If the comparison is false then the resulting value is 0,if true, the value is 1. Se il confronto è falso allora il valore risultante è 0, se vero, il valore è 1.
Here are the relational operations in C, Qui ci sono le operazioni relazionali in C,
> greater than > Superiore a
>= greater than or equal to > = Maggiore o uguale a
< less that <Meno che
<= less than or equal to <= Minore o uguale a
== equal to == Uguale a
!= not equal to ! = Non uguale a
Now, the question is, how to use these in C. Ora, la questione è, come utilizzare questi in C. If and Else Se e Else
Modify sum.c,edit as follows, Modifica sum.c, modificare come segue, CODE : CODICE:
#include <stdio.h># include <stdio.h>
main()main () {( float a,b,ratio;float a, b, rapporto;
printf("Enter two numbers: ");printf ( "Inserisci due numeri:"); scanf("%d %d", &a,&b);scanf ( "% d% d", & a, & b); ratio = a / b;ratio = a / b; if (b == 0)if (b == 0) printf("nInvalid Inputs!");printf ( "nInvalid Ingressi!"); elsealtro printf("nThe ratio is %d", ratio);printf ( "nIl messaggio rapporto è% d", rapporto); })
Save this as ratio.c Salva come ratio.c
We all know that in division, we cannot divide a number by 0, so in our program, we made use of conditional statements to avoid this mistake. Sappiamo tutti che nella divisione, non si può dividere un numero da 0, così nel nostro programma, abbiamo fatto uso del condizionale dichiarazioni per evitare questo errore. CODE : CODICE:
if (b == 0)if (b == 0) printf("nInvalid Inputs!");printf ( "nInvalid Ingressi!"); elsealtro printf("nThe ratio is %d", ratio);printf ( "nIl messaggio rapporto è% d", rapporto);
This is a conditional statement. Questo è un condizionale.It says that if b (which is the divisor) is equal to 0, then the statement/s under these will be executed, in the other hand, if it is false, the statement/s under else will be executed. Si dice che se B (che è il divisore) è pari a 0, allora l'affermazione / s in queste verrà eseguito, in altra parte, se è falso, la dichiarazione / s sotto altro verrà eseguito.
NOTE: In conditional statements, else can be optional. NOTA: In condizionato le dichiarazioni, gli altri possono essere facoltativi.
So, if the user entered 0 as a divisor(b), an error message will be displayed. Quindi, se l'utente è entrato 0 come divisore (b), un messaggio di errore verrà visualizzato.
The conditional statement's syntax is, Il condizionale è la sintassi, CODE : CODICE:
if(expression)if (espressione)
sets of statements;serie di dichiarazioni;
elsealtro
sets of statements;serie di dichiarazioni;
If the statements under each condition are more than 1, brackets should be placed. Se le dichiarazioni sotto ogni condizione sono più di 1, tra parentesi dovrà essere collocato.
NOTE: If and else doesnt need to have semicolons. NOTA: Se e altro doesn't necessità di disporre di un punto e virgola.
Logical Operators Operatori logici
There are also three logical operators, Ci sono anche tre operatori logici,
&& AND & & E
|| OR | | O
! NOT NON
These operators allows you to combine relational expresiions. Questi operatori vi permette di combinare expresiions relazionale.
AND E
true && true = true vero & & vero = true
true && false = false vero e falso & = false
false && true = false false & & vero = false
false && false = false false & & false = false
OR O
true && true = true vero & & vero = true
true && false = true vero e falso & = true
false && true = true false & & vero = true
false && false = false false & & false = false
NOT NON
!true = false ! vero = false
!false = true ! false = true
The examples above should be up to you to understand because its logical..=) Gli esempi di cui sopra dovrebbe essere a voi per capire perché la sua logica ..=)
We had tackled about programs that executes conditionally (conditional statements), but now, how would you like to know programs that executes repeatedly. Avevamo affrontato sui programmi che esegue condizionale (condizionato dichiarazioni), ma ora, come volete conoscere i programmi che esegue ripetutamente.These are Loops. Si tratta di loop.
There are three basic kinds of loops. Ci sono tre tipi fondamentali di loop.
while loop, ciclo while,
for loop, per ciclo,
do..while loop fare .. ciclo while While Loop Mentre Loop
Lets talk about the while loop. Consente di parlare del ciclo while.The while loop is the most general loop, and it can be used to replace the other two, in other words, the other two are only for special cases, but this loop can do the functions of the other two. Il ciclo while è il ciclo più generale, e può essere utilizzato per sostituire gli altri due, in altre parole, gli altri due sono solo per casi particolari, ma questo ciclo può fare le funzioni degli altri due.
Here is an example, Ecco un esempio, CODE : CODICE:
#include <stdio.h># include <stdio.h>
main()main () {( int length;int lunghezza; length = 0;lunghezza = 0; puts("Enter a string and press ENTER :");pone ( "Immettere una stringa e premere INVIO:"); while (getchar() != 'n')while (getchar ()! = 'n') length++;lunghezza + +; printf("nYour Sentence was %d characters long" length);printf ( "nYour frase era% d caratteri" lunghezza); })
This program lets you type a string and counts how many characters does your string have until you press ENTER. Questo programma vi permette di digitare una stringa e conta il numero di caratteri non sono il vostro stringa fino a quando non si premere INVIO.pretty great huh.. piuttosto grande eh ..
Just like conditional statements, loops also consider expressions, when the expression is false, it escapes the loop, and until the expression is true, it will repeatedly execute the statements under the loop. Proprio come le dichiarazioni condizionali, loop anche prendere in considerazione le espressioni, quando l'espressione è falsa, che sfugge il loop, e fino a quando l'espressione è vero, si eseguono ripetutamente le dichiarazioni sotto il loop. For Loop Per Loop
Lets move on to the for loop. Consente di passare al ciclo for.Consider this example. Considera questo esempio. CODE : CODICE:
#include <stdio.h># include <stdio.h>
main()main () {( int length;int lunghezza;
puts("Enter a string and press ENTER :");pone ( "Immettere una stringa e premere INVIO:"); for(length = 0;getchar() != 'n';length++)per (lunghezza = 0; getchar ()! = 'n'; lunghezza + +) {( }) printf("nYour Sentence was %d characters long", length);printf ( "nYour frase era% d caratteri", lunghezza); })
This example functions the same as the previous program, but here, we used for loop instead of while loop. Questo esempio funzioni lo stesso del precedente programma, ma in questo caso, abbiamo utilizzato per il ciclo invece di ciclo while.As you can see, for loop merges 3 statements into one parenthesis. Come si può vedere, per il ciclo si fonde 3 dichiarazioni in una parentesi.The for loop uses these statements as a condition to control the loop in the inner statements. Il circuito utilizza per queste dichiarazioni come una condizione per il controllo dei loop nel centro dichiarazioni.At our example, we don't need statements so we've just inserted the brackets. Nel nostro esempio, non abbiamo bisogno di dichiarazioni così abbiamo appena inserito le staffe.
NOTE: For that, if you will not put brackets, the compiler will consider the next statement as a statement of the for loop. NOTA: Per questo, se non mettere tra parentesi, il compilatore prenderà in considerazione la prossima dichiarazione come una dichiarazione del ciclo for.
The question, Why use for loop instead of just while loop? La questione, Perché usare per loop, invece di solo ciclo while?As i have said earlier, the two other loops are used in special cases, some uses of for loop are multidimensional arrays(advanced topic :: you will learn this soon). Come ho già detto in precedenza, gli altri due anelli sono utilizzati in casi particolari, alcuni utilizzi del ciclo for sono array multidimensionali (argomento avanzato: si impara presto questo). Do..While Loop Fare .. ciclo while
Now, what if you want to have a special function to halt your program?. Ora, se ciò che si desidera avere una funzione speciale per fermare il programma?.Use the do while loop.. Utilizzare il ciclo while fare ..
Here is an example, Ecco un esempio, CODE : CODICE:
#include <stdio.h># include <stdio.h>
main()main () {( int a;int a; dofare {( a = 1;a = 1; printf("%dn", a);printf ( "% dn", a); printf("nPress 'x' to quit, any other key to continue");printf ( "nPress' x 'per uscire, qualsiasi altro tasto per continuare"); }) while (getch() != 'x');while (getch ()! = 'x'); })
If you will run this program, it will output 1 and ask you to press a key, if you choose 'x', the program will halt, on the other hand, if you press keys other than 'x', the code between do and while will repeat. Se si esegue questo programma, sarà uscita 1 e chiedere di premere un tasto, se si sceglie 'x', il programma si arresta, d'altro canto, se si preme i tasti diversi da 'x', il codice tra il fare e mentre lo ripeto.
NOTE: the while in the do while loop, requires a semicolon. NOTA: l'mentre nel fare ciclo while, richiede un punto e virgola.
+++++++++++++++++++++++ Functions Funzioni +++++++++++++++++++++++
In some reasons, you may have been tired and lazy in typing operations over and over again. In alcuni motivi, potrebbe essere stato pigro e stanco nel digitando le operazioni più e più volte.For that you can use functions. Per che è possibile utilizzare le funzioni.
Functions are like shortcuts, whenever you will use an operation, you will just have to call it, by its function name. Funzioni sono come tasti di scelta rapida, ogni volta che si può usare l'operazione, sarà sufficiente chiamare, dal suo nome di funzione.
Here is an example, Ecco un esempio,
CODE : CODICE:
#include <stdio.h># include <stdio.h>
void math_all(int a, int b);void math_all (int a, int b);
void math_all(int a,int b)void math_all (int a, int b) {( int sum,dif,pro,quo;int somma, dif, pro, quo;
sum = a + b;somma = a + b; dif = a - b;dif = a - b; pro = a * b;pro = a * b; quo = a / b;quo = a / b; printf("nThe Sum is %d",sum);printf ( "Somma nIl messaggio è% d", somma); printf("nThe Difference is %d",dif);printf ( "nIl messaggio Differenza è% d", dif); printf("nThe Product is %d",pro);printf ( "nIl messaggio prodotto è% d", pro); printf("nThe Quotient is %d",quo);printf ( "nIl messaggio Quoziente è% d", quo); })
Here, in our program, we made use of functions to call on different basic operations such as addition, subtraction, multiplication and division. Qui, nel nostro programma, abbiamo fatto uso delle funzioni di chiamata su diverse operazioni di base come addizione, sottrazione, moltiplicazione e divisione.As i mentioned earlier, functions are like shortcuts, analyze the code and see what i mean. Come ho già detto in precedenza, le funzioni sono come tasti di scelta rapida, analizzare il codice e vedere che cosa mi riferisco.
First, we declare the function, functions are declared globally, it means that it can be used in different parts of the program in and out the main().You may notice that we put the word "void" before the name,void means, it doesn't return any values at all. In primo luogo, dichiarare la funzione, le funzioni sono dichiarate a livello mondiale, ciò significa che esso può essere utilizzato in diverse parti del programma in entrata e in uscita il main (). Potete notare che abbiamo messo la parola "vuoto" prima del nome, significa nulla , Che non restituisce i valori a tutti.If the function returns a value, then we should put "int" before the name instead of void. Se la funzione restituisce un valore, allora dobbiamo mettere "int" prima del nome, invece di nulla.After we have declared it, we can use it in main. Dopo aver dichiarato, si possono utilizzare in principali.
In main, we made use of scanf to get the value of the two numbers (c and d), then we passed the value to a and b, which are variables of the function math_all(). In principale, abbiamo fatto uso di scanf per ottenere il valore dei due numeri (C e D), quindi abbiamo superato il valore di A e B, che sono le variabili della funzione math_all ().
Next, we defined the function, its more like telling the compiler what does the function do. Quindi, abbiamo definito la funzione, la sua più come dice il compilatore che cosa consiste la funzione di fare.It usually composed of Operations and different library functions. E 'composto di solito le operazioni e le diverse funzioni di libreria.
TIP: You can declare and define a function anywhere in the SUGGERIMENTO: È possibile dichiarare e definire una funzione in qualsiasi parte del program. programma.
So far, we have discussed about variables that holds data, well, in this chapter, we will discuss variables that holds address of data,Pointers. Finora, abbiamo discusso circa le variabili che contiene dati, beh, in questo capitolo, si discuteranno le variabili che contiene l'indirizzo dei dati, Puntatori.
Before we define pointers, lets have a quick glance about the memory. Prima di definire i puntatori, consente di avere un rapido sguardo sulla memoria. Memory Lookup Memoria di ricerca
Computers hold programs and data in its memory, also called RAM - Random Access Memory. Computer tenere programmi e dati nella sua memoria, detta anche RAM - Random Access Memory.The computers memory, at its lowest level, are composed of bits,microscopic electronic circuits, bits are from Binary digITs. La memoria dei computer, al suo livello più basso, si compone di bit, microscopici circuiti elettronici, i bit sono da cifre binarie.
Bits can remeber one of two values (1 and 0), you may have seen numbers written horizontally of vertically composed of 1's and 0's. Bit può ricordare uno dei due valori (1 e 0), è possibile che hanno visto i numeri scritti in orizzontale verticale del composto di 1 e di 0.Example, Esempio,
11011010
These are bits, and every 8 bits of them are called bytes, if you want to know more of this, do search for binary numbers and find tutorials. Si tratta di bit, e ogni 8 bit di essi sono chiamati byte, se volete saperne di più di questo, fare ricerca di numeri binari e trovare tutorial.Each byte in a computer's memory has a unique address -- Usually Hexadecimal Format, hexadecimal characters like 166EE can be converted to bits and vice versa. Ciascun byte in una memoria del computer ha un indirizzo univoco - Di solito formato esadecimale, come caratteri esadecimali 166EE possono essere convertiti in bit e viceversa.You can have a binary conversion table in the net, if you want, go search for it. È possibile avere una tabella di conversione binario nella rete, se vuoi, vai ricerca di essa. Define Pointers Definire Puntatori
A pointer is a variable that holds the address of some data, rather than the data itself. Un puntatore è una variabile che contiene l'indirizzo di alcuni dati, piuttosto che i dati stessi.But you would ask yourself, Why is it important and how to use it? Ma si dovrebbe chiedere se, Perché è importante e come utilizzarlo?
You can use pointer to point to different data and different data structures. È possibile utilizzare il puntatore al punto di dati diversi e diverse strutture di dati.By changing the address the pointer contains, you can manipulate information in various locations. Modificando l'indirizzo contiene il puntatore, è possibile manipolare le informazioni in varie località.
Lets see an example of pointers, Consente di visualizzare un esempio di puntatori,
CODE : CODICE:
#include <stdio.h># include <stdio.h>
main()main () {( int a, *pa;int uno, * PA;
a = 9;a = 9; pa = &a;pa = &a; printf("%p", pa);printf ( "% p", pa); })
In this example, we had an output of a memory address, address of 9. In questo esempio, abbiamo avuto una produzione di un indirizzo di memoria, l'indirizzo del 9.Since we have to output an address, we have to use the format specification %p for pointers. Dal momento che abbiamo per produrre in output un indirizzo, dobbiamo utilizzare il formato% p per i puntatori.When we declare pointers, we should put an asterisk * before it. Quando abbiamo dichiarare puntatori, dovremmo mettere un asterisco * dinanzi ad esso.
TIP: In declaring pointers, practice using names starting with p, example, *pa. SUGGERIMENTO: In che dichiara i puntatori, le pratiche con nomi che iniziano con p, ad esempio, * pa.
If you want to output the data of the address held by the pointer you should write, Se si desidera l'uscita di dati l'indirizzo detenute da il puntatore si dovrebbe scrivere,
CODE : CODICE:
printf("%d", &*pa);printf ( "% d", & * pa);
Since you will output a data which is an integer, you should use %d specification. Visto che si visualizzerà una banca dati che è un numero intero, si dovrebbe usare% d disciplinare.
When you assign a varaiable to a pointer, make sure you have this format, Quando si assegna un varaiable di un puntatore, assicurati di avere questo formato,
pointer = address of variable(&) puntatore = indirizzo della variabile (&)
or o
Value of pointer(*) = variable Valore del puntatore (*) = variabile
Statements above represents this, Le dichiarazioni di cui sopra rappresenta questo,
CODE : CODICE:
pa = &a;pa = &a;
or o
CODE : CODICE:
*pa = a;* pa = a;
Get it? Ordinare?
After you have finished this tutorials, i recommend to read more advanced tutorials on pointers(since this tutorial is for beginners - basic - only). Dopo avere finito questo tutorial, raccomando di leggere più avanzati tutorial su puntatori (dato che questo tutorial è per i principianti - di base - solo).
An array is an example of a homogeneous random access data structure. Un array è un esempio di un accesso casuale omogenea struttura di dati.An array is merely a collection of similar data elements such as integers, floats, characters, etc. which is stored together with a common name, and addressed by means of index that tells the location of the particular data entity in the array. Un array è solo una raccolta di dati simili elementi come numeri interi, galleggianti, caratteri, ecc, che è memorizzato insieme con un nome comune, e affrontati da mezzi di indice che indica l'ubicazione dei dati di particolare entità in array.
When we use homogeneous to an array, it means that each cells have the same data type, and the random-access aspect tells that we can access any of the cells of an array directly by just using its indices. Quando usiamo omogeneo di un array, ciò significa che ogni cellule hanno lo stesso tipo di dati, e l'ad accesso casuale aspetto dice che siamo in grado di accedere a qualsiasi delle cellule di un array direttamente da solo utilizzando il proprio indici.
Example, Esempio, CODE : CODICE:
#include <stdio.h># include <stdio.h>
main()main () {( int a[50];int a [50]; a[0] = 19;a [0] = 19; })
Now, what have we done?, well, we assigned a data to an array. Ora, che cosa abbiamo fatto?, Beh, abbiamo assegnato una banca dati di un array.
NOTE: an array starts from 0. NOTA: un array inizia da 0.Example, in array a[50], the first block starts from a[0] and ends in a[49]. Esempio, in uno array [50], il primo blocco parte da una [0] e termina in un [49].Why 49? Perché 49?as we declared a[50], we declared 50 blocks, and in an array, the end must be a NULL character . come abbiamo dichiarato [50], ha dichiarato che 50 blocchi, e in un array, la fine deve essere un carattere NULL.So, we started from 0 and end in 49 to make 50 a null character. Allora, abbiamo iniziato da 0 e termina in 49 per fare 50 al carattere null.
If you would visualize the arrays as horizontal blocks, and you addressed 1