logo

Struttura C

Perché usare la struttura?

In C, ci sono casi in cui dobbiamo memorizzare più attributi di un'entità. Non è necessario che un'entità abbia tutte le informazioni di un solo tipo. Può avere diversi attributi di diversi tipi di dati. Ad esempio, un'entità Alunno può avere il suo nome (string), numero di rotolo (int), segni (float). Per archiviare questo tipo di informazioni relative a uno studente dell'entità, abbiamo i seguenti approcci:

  • Costruisci array individuali per memorizzare nomi, numeri di rotolo e segni.
  • Utilizzare una struttura dati speciale per archiviare la raccolta di diversi tipi di dati.

Vediamo nel dettaglio il primo approccio.

 #include void main () { char names[2][10],dummy; // 2-dimensioanal character array names is used to store the names of the students int roll_numbers[2],i; float marks[2]; for (i=0;i<3;i++) { printf('enter the name, roll number, and marks of student %d',i+1); scanf('%s %d %f',&names[i],&roll_numbers[i],&marks[i]); scanf('%c',&dummy); enter will be stored into dummy character at each iteration } printf('printing details ...
'); for (i="0;i&lt;3;i++)" printf('%s %f
',names[i],roll_numbers[i],marks[i]); < pre> <p> <strong>Output</strong> </p> <pre> Enter the name, roll number, and marks of the student 1Arun 90 91 Enter the name, roll number, and marks of the student 2Varun 91 56 Enter the name, roll number, and marks of the student 3Sham 89 69 Printing the Student details... Arun 90 91.000000 Varun 91 56.000000 Sham 89 69.000000 </pre> <p>The above program may fulfill our requirement of storing the information of an entity student. However, the program is very complex, and the complexity increase with the amount of the input. The elements of each of the array are stored contiguously, but all the arrays may not be stored contiguously in the memory. C provides you with an additional and simpler approach where you can use a special data structure, i.e., structure, in which, you can group all the information of different data type regarding an entity.</p> <h2>What is Structure</h2> <p>Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can store various information </p> <p>The <strong>,struct</strong> keyword is used to define the structure. Let&apos;s see the syntax to define the structure in c.</p> <pre> struct structure_name { data_type member1; data_type member2; . . data_type memeberN; }; </pre> <p>Let&apos;s see the example to define a structure for an entity employee in c.</p> <pre> struct employee { int id; char name[20]; float salary; }; </pre> <p>The following image shows the memory allocation of the structure employee that is defined in the above example.</p> <img src="//techcodeview.com/img/c-tutorial/01/c-structure.webp" alt="c structure memory allocation"> <p>Here, <strong>struct</strong> is the keyword; <strong>employee</strong> is the name of the structure; <strong>id</strong> , <strong>name</strong> , and <strong>salary</strong> are the members or fields of the structure. Let&apos;s understand it by the diagram given below:</p> <img src="//techcodeview.com/img/c-tutorial/01/c-structure-2.webp" alt="c structure"> <h2>Declaring structure variable</h2> <p>We can declare a variable for the structure so that we can access the member of the structure easily. There are two ways to declare structure variable:</p> <ol class="points"> <li>By struct keyword within main() function</li> <li>By declaring a variable at the time of defining the structure.</li> </ol> <p> <strong>1st way:</strong> </p> <p>Let&apos;s see the example to declare the structure variable by struct keyword. It should be declared within the main function.</p> <pre> struct employee { int id; char name[50]; float salary; }; </pre> <p>Now write given code inside the main() function.</p> <pre> struct employee e1, e2; </pre> <p>The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be treated in the same way as the objects in <a href="/c-tutorial">C++</a> and <a href="/java-tutorial">Java</a> .</p> <p> <strong>2nd way:</strong> </p> <p>Let&apos;s see another way to declare variable at the time of defining the structure.</p> <pre> struct employee { int id; char name[50]; float salary; }e1,e2; </pre> <h3>Which approach is good</h3> <p>If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the structure variable many times.</p> <p>If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main() function.</p> <h2>Accessing members of the structure</h2> <p>There are two ways to access structure members:</p> <ol class="points"> <li>By . (member or dot operator)</li> <li>By -&gt; (structure pointer operator)</li> </ol> <p>Let&apos;s see the code to access the <em>id</em> member of <em>p1</em> variable by. (member) operator.</p> <pre> p1.id </pre> <h3>C Structure example</h3> <p>Let&apos;s see a simple example of structure in C language.</p> <pre> #include #include struct employee { int id; char name[50]; }e1; //declaring e1 variable for structure int main( ) { //store first employee information e1.id=101; strcpy(e1.name, &apos;Sonoo Jaiswal&apos;);//copying string into char array //printing first employee information printf( &apos;employee 1 id : %d
&apos;, e1.id); printf( &apos;employee 1 name : %s
&apos;, e1.name); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> employee 1 id : 101 employee 1 name : Sonoo Jaiswal </pre> <p>Let&apos;s see another example of the structure in <a href="/c-programming-language-tutorial">C language</a> to store many employees information.</p> <pre> #include #include struct employee { int id; char name[50]; float salary; }e1,e2; //declaring e1 and e2 variables for structure int main( ) { //store first employee information e1.id=101; strcpy(e1.name, &apos;Sonoo Jaiswal&apos;);//copying string into char array e1.salary=56000; //store second employee information e2.id=102; strcpy(e2.name, &apos;James Bond&apos;); e2.salary=126000; //printing first employee information printf( &apos;employee 1 id : %d
&apos;, e1.id); printf( &apos;employee 1 name : %s
&apos;, e1.name); printf( &apos;employee 1 salary : %f
&apos;, e1.salary); //printing second employee information printf( &apos;employee 2 id : %d
&apos;, e2.id); printf( &apos;employee 2 name : %s
&apos;, e2.name); printf( &apos;employee 2 salary : %f
&apos;, e2.salary); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> employee 1 id : 101 employee 1 name : Sonoo Jaiswal employee 1 salary : 56000.000000 employee 2 id : 102 employee 2 name : James Bond employee 2 salary : 126000.000000 </pre> <hr></3;i++)>

Il programma di cui sopra può soddisfare la nostra esigenza di archiviare le informazioni di uno studente dell'entità. Tuttavia, il programma è molto complesso e la complessità aumenta con la quantità di input. Gli elementi di ciascun array vengono archiviati in modo contiguo, ma è possibile che non tutti gli array vengano archiviati in modo contiguo nella memoria. C fornisce un approccio aggiuntivo e più semplice in cui è possibile utilizzare una struttura dati speciale, ovvero una struttura, in cui è possibile raggruppare tutte le informazioni di diverso tipo di dati relative a un'entità.

Cos'è la struttura

La struttura in c è un tipo di dati definito dall'utente che ci consente di archiviare la raccolta di diversi tipi di dati. Ogni elemento di una struttura è chiamato membro. Strutture ca; simula l'uso di classi e modelli in quanto può memorizzare varie informazioni

IL ,struttura la parola chiave viene utilizzata per definire la struttura. Vediamo la sintassi per definire la struttura in c.

tutorial su ssis
 struct structure_name { data_type member1; data_type member2; . . data_type memeberN; }; 

Vediamo l'esempio per definire una struttura per un dipendente dell'entità in c.

 struct employee { int id; char name[20]; float salary; }; 

L'immagine seguente mostra l'allocazione di memoria dell'impiegato della struttura definita nell'esempio precedente.

allocazione della memoria della struttura c

Qui, struttura è la parola chiave; dipendente è il nome della struttura; id , nome , E stipendio sono i membri o i campi della struttura. Capiamolo dallo schema riportato di seguito:

commento PowerShell su più righe
struttura c

Dichiarare la variabile di struttura

Possiamo dichiarare una variabile per la struttura in modo da poter accedere facilmente al membro della struttura. Esistono due modi per dichiarare la variabile di struttura:

  1. Tramite la parola chiave struct all'interno della funzione main()
  2. Dichiarando una variabile al momento della definizione della struttura.

1° modo:

Vediamo l'esempio per dichiarare la variabile di struttura tramite la parola chiave struct. Dovrebbe essere dichiarato all'interno della funzione principale.

 struct employee { int id; char name[50]; float salary; }; 

Ora scrivi il codice dato all'interno della funzione main().

 struct employee e1, e2; 

Le variabili e1 ed e2 possono essere utilizzate per accedere ai valori memorizzati nella struttura. Qui, e1 ed e2 possono essere trattati allo stesso modo degli oggetti in C++ E Giava .

2° modo:

Vediamo un altro modo di dichiarare la variabile al momento della definizione della struttura.

 struct employee { int id; char name[50]; float salary; }e1,e2; 

Quale approccio è buono

Se il numero di variabili non è fisso, utilizzare il primo approccio. Ti offre la flessibilità di dichiarare la variabile della struttura più volte.

Se no. di variabili sono fisse, utilizzare il 2° approccio. Salva il tuo codice per dichiarare una variabile nella funzione main().

Accesso ai membri della struttura

Esistono due modi per accedere ai membri della struttura:

attraversamento dell'albero in ordine
  1. Di . (membro o operatore punto)
  2. By -> (operatore puntatore a struttura)

Vediamo il codice per accedere al id membro di p1 variabile di. operatore (membro).

 p1.id 

Esempio di struttura C

Vediamo un semplice esempio di struttura in linguaggio C.

 #include #include struct employee { int id; char name[50]; }e1; //declaring e1 variable for structure int main( ) { //store first employee information e1.id=101; strcpy(e1.name, &apos;Sonoo Jaiswal&apos;);//copying string into char array //printing first employee information printf( &apos;employee 1 id : %d
&apos;, e1.id); printf( &apos;employee 1 name : %s
&apos;, e1.name); return 0; } 

Produzione:

 employee 1 id : 101 employee 1 name : Sonoo Jaiswal 

Vediamo un altro esempio della struttura in Linguaggio C per memorizzare molte informazioni sui dipendenti.

 #include #include struct employee { int id; char name[50]; float salary; }e1,e2; //declaring e1 and e2 variables for structure int main( ) { //store first employee information e1.id=101; strcpy(e1.name, &apos;Sonoo Jaiswal&apos;);//copying string into char array e1.salary=56000; //store second employee information e2.id=102; strcpy(e2.name, &apos;James Bond&apos;); e2.salary=126000; //printing first employee information printf( &apos;employee 1 id : %d
&apos;, e1.id); printf( &apos;employee 1 name : %s
&apos;, e1.name); printf( &apos;employee 1 salary : %f
&apos;, e1.salary); //printing second employee information printf( &apos;employee 2 id : %d
&apos;, e2.id); printf( &apos;employee 2 name : %s
&apos;, e2.name); printf( &apos;employee 2 salary : %f
&apos;, e2.salary); return 0; } 

Produzione:

 employee 1 id : 101 employee 1 name : Sonoo Jaiswal employee 1 salary : 56000.000000 employee 2 id : 102 employee 2 name : James Bond employee 2 salary : 126000.000000