logo

Dynamisches Array in C

Dynamische Arrays sind eine leistungsstarke Datenstruktur in der Programmierung, die dies ermöglicht Erstellen Und manipulieren Arrays unterschiedlicher Größe zur Laufzeit. In C werden dynamische Arrays mithilfe von Zeigern und Speicherzuweisungsfunktionen implementiert, was sie zu einem wertvollen Werkzeug zur Optimierung der Speichernutzung und zur Erstellung effizienter Programme macht. In diesem Artikel untersuchen wir das Konzept dynamischer Arrays in C, ihre Vor- und Nachteile und wie man sie erstellt und manipuliert.

Dynamische Arrays verstehen

A dynamisches Array ist ein Array, dessen Größe während geändert werden kann Laufzeit . nicht wie statische Arrays Da dynamische Arrays eine feste Größe haben, die zur Kompilierungszeit festgelegt wird, kann die Größe dynamischer Arrays nach Bedarf geändert werden. Es ermöglicht mehr Flexibilität und eine bessere Speicherverwaltung, da die Größe des Arrays an die gespeicherte Datenmenge angepasst werden kann.

Dynamische Arrays werden mithilfe von Zeigern und Speicherzuweisungsfunktionen implementiert. In C sind dies die am häufigsten verwendeten Speicherzuweisungsfunktionen malloc() , calloc() , Und realloc() . Diese Funktionen ermöglichen die Zuweisung und Freigabe von Speicher zur Laufzeit, was zum Erstellen und Bearbeiten dynamischer Arrays erforderlich ist.

Vorteile dynamischer Arrays

Die Verwendung dynamischer Arrays in C bietet mehrere Vorteile. Einige der Hauptvorteile sind folgende:

  1. Einer der Hauptvorteile besteht darin, dass sie eine bessere Speicherverwaltung ermöglichen. Bei statischen Arrays beträgt die Größe des Arrays Fest , was bedeutet, dass dem gesamten Array auf einmal Speicher zugewiesen wird. Wenn das Array nicht vollständig ausgelastet ist, kann es zu Speicherverschwendung kommen.
  2. Bei dynamischen Arrays wird Speicher nur nach Bedarf zugewiesen, was zu einer effizienteren Speichernutzung führen kann.
  3. Dynamische Arrays ermöglichen außerdem eine größere Flexibilität.
  4. Dies kann einschränkend sein, insbesondere wenn sich die Größe des Arrays während der Laufzeit ändern muss.
  5. Dynamische Arrays ermöglichen die Anpassung der Array-Größe nach Bedarf, wodurch Programme vielseitiger und anpassungsfähiger werden können.

Nachteile dynamischer Arrays

Während dynamische Arrays viele Vorteile haben, haben sie auch einige Nachteile. Einige der Hauptnachteile sind folgende:

Ersetzen Sie aus einer Zeichenfolge in Java
  1. Einer der Hauptnachteile besteht darin, dass ihre Implementierung komplexer sein kann als statische Arrays.
  2. Dynamische Arrays erfordern die Verwendung von Hinweise Und Speicherzuweisungsfunktionen , was schwieriger zu verstehen und zu verwenden sein kann als die einfache Array-Syntax statischer Arrays.
  3. Dynamische Arrays können auch langsamer sein als statische Arrays. Da die Speicherzuweisung und -freigabe erforderlich ist, sind mit der Verwendung dynamischer Arrays Mehrkosten verbunden. Dieser Mehraufwand kann dazu führen, dass dynamische Arrays in manchen Fällen langsamer sind als statische Arrays.

Dynamische Arrays in C erstellen

Um ein dynamisches Array in C zu erstellen, müssen wir verwenden Speicherzuweisungsfunktionen um Speicher für das Array zu reservieren. Die am häufigsten verwendeten Speicherzuweisungsfunktionen in C sind malloc(), calloc() , Und realloc() . Hier ist ein Beispiel für die Erstellung eines dynamischen Arrays mit malloc():

'ABC's in Zahlen'
 int *arr; int size = 10; arr = (int*) malloc(size * sizeof(int)); 

Erläuterung:

In diesem Beispiel deklarieren wir einen Zeiger auf ein Integer-Array namens arr . Wir deklarieren auch eine Ganzzahlvariable namens Größe , was die Größe des Arrays darstellt, das wir erstellen möchten. Danach verwenden wir die malloc() Funktion zum Zuweisen von Speicher für das Array. Der malloc() Die Funktion nimmt die Größe des Arrays an (in Bytes ) als Argument, also multiplizieren wir die Größe des Arrays mit der Größe einer Ganzzahl (d. h 4 Bytes auf den meisten Systemen), um die Gesamtgröße in Bytes zu erhalten.

Bearbeiten dynamischer Arrays in C

Sobald wir ein dynamisches Array in C erstellt haben, können wir es wie jedes andere Array bearbeiten. Mit der Array-Syntax können wir auf einzelne Elemente des Arrays zugreifen:

 arr[0] = 5; 

In diesem Beispiel setzen wir das erste Element des Arrays auf 5 .

Wir können auch verwenden Schleifen um über das Array zu iterieren:

str.substring in Java
 for (int i = 0; i<size; i++) { arr[i]="i" * 2; } < pre> <p>In this example, we use a <strong> <em>for loop</em> </strong> to set each element of the array to twice its index.</p> <p>To resize a dynamic array in C, we can use the <strong> <em>realloc()</em> </strong> function. The <strong> <em>realloc()</em> </strong> function takes two arguments: a <strong> <em>pointer</em> </strong> to the original memory block and the <strong> <em>new size</em> </strong> of the memory block. Here is an example of how to resize a dynamic array using realloc():</p> <pre> int new_size = 20; arr = (int*) realloc(arr, new_size * sizeof(int)); </pre> <p>In this example, we declare a new integer variable called <strong> <em>new_size</em> </strong> , which represents the new size of the array. After that, we use the <strong> <em>realloc() function</em> </strong> to resize the array. The <strong> <em>realloc() function</em> </strong> takes the pointer to the original memory block (in this case, <strong> <em>arr</em> </strong> ) and the <strong> <em>new size</em> </strong> of the memory block (in <strong> <em>bytes</em> </strong> ). We multiply the <strong> <em>new size</em> </strong> of the array by the <strong> <em>size</em> </strong> of an <strong> <em>integer</em> </strong> to get the total size in bytes.</p> <p>It is important to note that when we resize a dynamic array using <strong> <em>realloc()</em> </strong> , any existing data in the array will be preserved. If the new size of the array is larger than the original size, the new elements will be uninitialized.</p> <p>To free the memory used by a dynamic array in C, we can use the <strong> <em>free()</em> </strong> function. The <strong> <em>free()</em> </strong> function takes a pointer to the memory block that was allocated using <strong> <em>malloc()</em> </strong> , <strong> <em>calloc()</em> </strong> , or <strong> <em>realloc()</em> </strong> . Here is an example of how to free the memory used by a dynamic array:</p> <pre> free(arr); </pre> <p>In this example, we use the <strong> <em>free() function</em> </strong> to free the memory used by the dynamic array <strong> <em>arr</em> </strong> . It is important to note that once we have freed the memory used by a dynamic array, we should not attempt to access the elements of the array.</p> <h3>Some more examples of using dynamic arrays in C:</h3> <p> <strong>Adding Elements to a Dynamic Array:</strong> </p> <p>One of the main benefits of using a dynamic array is the ability to add elements to the array as needed. Here is an example of how to add an element to a dynamic array:</p> <pre> #include #include int main() { int size = 5; int *arr = (int*) malloc(size * sizeof(int)); int i; for(i = 0; i<size; i++) { arr[i]="i;" } add a new element to the array size++; arr="(int*)" realloc(arr, size * sizeof(int)); arr[size-1]="i;" for(i="0;" i< size; printf('%d ', arr[i]); free(arr); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, we first create a dynamic array <strong> <em>arr</em> </strong> of size <strong> <em>5</em> </strong> using the <strong> <em>malloc()</em> </strong> function. After that, we set each element of the array to its index using a <strong> <em>for loop</em> </strong> . To add a new element to the array, we increment the size of the array by one and use the <strong> <em>realloc() function</em> </strong> to resize the array. We set the value of the last element in the array to the current value of <strong> <em>i</em> </strong> . Finally, we print the contents of the array and free the memory used by the array.</p> <h3>Resizing a Dynamic Array</h3> <p>Another advantage of using a dynamic array is the ability to resize the array as needed. Here is an example of how to resize a dynamic array:</p> <pre> #include #include int main() { int size = 5; int *arr = (int*) malloc(size * sizeof(int)); int i; for(i = 0; i<size; i++) { arr[i]="i;" } resize the array size="10;" arr="(int*)" realloc(arr, * sizeof(int)); for(i="5;" i< size; printf('%d ', arr[i]); free(arr); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 5 6 7 8 9 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, we first create a dynamic array <strong> <em>arr</em> </strong> of size <strong> <em>5</em> </strong> using the <strong> <em>malloc() function</em> </strong> . After that, we set each element of the array to its index using a <strong> <em>for loop</em> </strong> . To resize the array, we set the value of size to <strong> <em>10</em> </strong> and use the <strong> <em>realloc()</em> </strong> function to resize the array. After that, we set the value of the new elements in the array using another for loop. Finally, we print the contents of the array and free the memory used by the array.</p> <h2>Conclusion</h2> <p> <strong> <em>Dynamic arrays</em> </strong> are a powerful data structure in programming that allow for the creation and manipulation of arrays of varying sizes during runtime. In C, dynamic arrays are implemented using pointers and memory allocation functions, making them a valuable tool for optimizing memory usage and creating efficient programs.</p> <p>While <strong> <em>dynamic arrays</em> </strong> have many advantages, they also have some disadvantages. Dynamic arrays can be more complex to implement than static arrays and can be slower in some cases. However, the flexibility and efficiency of dynamic arrays make them a valuable tool for many programming tasks.</p> <p>To create and manipulate dynamic arrays in C, we must use memory allocation functions to allocate and deallocate memory during runtime. The most commonly used memory allocation functions in C are <strong> <em>malloc()</em> </strong> , <strong> <em>calloc()</em> </strong> , and <strong> <em>realloc()</em> </strong> . It is important to properly manage memory usage when working with dynamic arrays to avoid memory leaks and other memory-related issues.</p> <hr></size;></pre></size;></pre></size;>

In diesem Beispiel deklarieren wir eine neue Ganzzahlvariable namens neue_größe , was die neue Größe des Arrays darstellt. Danach verwenden wir die realloc()-Funktion um die Größe des Arrays zu ändern. Der realloc()-Funktion Nimmt den Zeiger auf den ursprünglichen Speicherblock (in diesem Fall arr ) und das neue Größe des Speicherblocks (in Bytes ). Wir multiplizieren die neue Größe des Arrays durch die Größe eines ganze Zahl um die Gesamtgröße in Bytes zu erhalten.

Es ist wichtig zu beachten, dass wir die Größe eines dynamischen Arrays mit ändern realloc() , bleiben alle vorhandenen Daten im Array erhalten. Wenn die neue Größe des Arrays größer als die ursprüngliche Größe ist, werden die neuen Elemente nicht initialisiert.

Um den von einem dynamischen Array in C verwendeten Speicher freizugeben, können wir Folgendes verwenden frei() Funktion. Der frei() Die Funktion nimmt einen Zeiger auf den Speicherblock, der mit zugewiesen wurde malloc() , calloc() , oder realloc() . Hier ist ein Beispiel dafür, wie Sie den von einem dynamischen Array verwendeten Speicher freigeben:

 free(arr); 

In diesem Beispiel verwenden wir die free()-Funktion um den vom dynamischen Array verwendeten Speicher freizugeben arr . Es ist wichtig zu beachten, dass wir nicht versuchen sollten, auf die Elemente des Arrays zuzugreifen, sobald wir den von einem dynamischen Array verwendeten Speicher freigegeben haben.

Einige weitere Beispiele für die Verwendung dynamischer Arrays in C:

Elemente zu einem dynamischen Array hinzufügen:

Einer der Hauptvorteile der Verwendung eines dynamischen Arrays ist die Möglichkeit, dem Array nach Bedarf Elemente hinzuzufügen. Hier ist ein Beispiel für das Hinzufügen eines Elements zu einem dynamischen Array:

arp-a-Befehl
 #include #include int main() { int size = 5; int *arr = (int*) malloc(size * sizeof(int)); int i; for(i = 0; i<size; i++) { arr[i]="i;" } add a new element to the array size++; arr="(int*)" realloc(arr, size * sizeof(int)); arr[size-1]="i;" for(i="0;" i< size; printf(\'%d \', arr[i]); free(arr); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, we first create a dynamic array <strong> <em>arr</em> </strong> of size <strong> <em>5</em> </strong> using the <strong> <em>malloc()</em> </strong> function. After that, we set each element of the array to its index using a <strong> <em>for loop</em> </strong> . To add a new element to the array, we increment the size of the array by one and use the <strong> <em>realloc() function</em> </strong> to resize the array. We set the value of the last element in the array to the current value of <strong> <em>i</em> </strong> . Finally, we print the contents of the array and free the memory used by the array.</p> <h3>Resizing a Dynamic Array</h3> <p>Another advantage of using a dynamic array is the ability to resize the array as needed. Here is an example of how to resize a dynamic array:</p> <pre> #include #include int main() { int size = 5; int *arr = (int*) malloc(size * sizeof(int)); int i; for(i = 0; i<size; i++) { arr[i]="i;" } resize the array size="10;" arr="(int*)" realloc(arr, * sizeof(int)); for(i="5;" i< size; printf(\'%d \', arr[i]); free(arr); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 5 6 7 8 9 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, we first create a dynamic array <strong> <em>arr</em> </strong> of size <strong> <em>5</em> </strong> using the <strong> <em>malloc() function</em> </strong> . After that, we set each element of the array to its index using a <strong> <em>for loop</em> </strong> . To resize the array, we set the value of size to <strong> <em>10</em> </strong> and use the <strong> <em>realloc()</em> </strong> function to resize the array. After that, we set the value of the new elements in the array using another for loop. Finally, we print the contents of the array and free the memory used by the array.</p> <h2>Conclusion</h2> <p> <strong> <em>Dynamic arrays</em> </strong> are a powerful data structure in programming that allow for the creation and manipulation of arrays of varying sizes during runtime. In C, dynamic arrays are implemented using pointers and memory allocation functions, making them a valuable tool for optimizing memory usage and creating efficient programs.</p> <p>While <strong> <em>dynamic arrays</em> </strong> have many advantages, they also have some disadvantages. Dynamic arrays can be more complex to implement than static arrays and can be slower in some cases. However, the flexibility and efficiency of dynamic arrays make them a valuable tool for many programming tasks.</p> <p>To create and manipulate dynamic arrays in C, we must use memory allocation functions to allocate and deallocate memory during runtime. The most commonly used memory allocation functions in C are <strong> <em>malloc()</em> </strong> , <strong> <em>calloc()</em> </strong> , and <strong> <em>realloc()</em> </strong> . It is important to properly manage memory usage when working with dynamic arrays to avoid memory leaks and other memory-related issues.</p> <hr></size;></pre></size;>

Erläuterung:

In diesem Beispiel erstellen wir zunächst ein dynamisches Array arr der Größe 5 Verwendung der malloc() Funktion. Danach setzen wir jedes Element des Arrays mit a auf seinen Index for-Schleife . Um dem Array ein neues Element hinzuzufügen, erhöhen wir die Größe des Arrays um eins und verwenden das realloc()-Funktion um die Größe des Arrays zu ändern. Wir setzen den Wert des letzten Elements im Array auf den aktuellen Wert von ich . Schließlich drucken wir den Inhalt des Arrays aus und geben den vom Array verwendeten Speicher frei.

Ändern der Größe eines dynamischen Arrays

Ein weiterer Vorteil der Verwendung eines dynamischen Arrays ist die Möglichkeit, die Größe des Arrays nach Bedarf zu ändern. Hier ist ein Beispiel für die Größenänderung eines dynamischen Arrays:

 #include #include int main() { int size = 5; int *arr = (int*) malloc(size * sizeof(int)); int i; for(i = 0; i<size; i++) { arr[i]="i;" } resize the array size="10;" arr="(int*)" realloc(arr, * sizeof(int)); for(i="5;" i< size; printf(\'%d \', arr[i]); free(arr); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 5 6 7 8 9 </pre> <p> <strong>Explanation:</strong> </p> <p>In this example, we first create a dynamic array <strong> <em>arr</em> </strong> of size <strong> <em>5</em> </strong> using the <strong> <em>malloc() function</em> </strong> . After that, we set each element of the array to its index using a <strong> <em>for loop</em> </strong> . To resize the array, we set the value of size to <strong> <em>10</em> </strong> and use the <strong> <em>realloc()</em> </strong> function to resize the array. After that, we set the value of the new elements in the array using another for loop. Finally, we print the contents of the array and free the memory used by the array.</p> <h2>Conclusion</h2> <p> <strong> <em>Dynamic arrays</em> </strong> are a powerful data structure in programming that allow for the creation and manipulation of arrays of varying sizes during runtime. In C, dynamic arrays are implemented using pointers and memory allocation functions, making them a valuable tool for optimizing memory usage and creating efficient programs.</p> <p>While <strong> <em>dynamic arrays</em> </strong> have many advantages, they also have some disadvantages. Dynamic arrays can be more complex to implement than static arrays and can be slower in some cases. However, the flexibility and efficiency of dynamic arrays make them a valuable tool for many programming tasks.</p> <p>To create and manipulate dynamic arrays in C, we must use memory allocation functions to allocate and deallocate memory during runtime. The most commonly used memory allocation functions in C are <strong> <em>malloc()</em> </strong> , <strong> <em>calloc()</em> </strong> , and <strong> <em>realloc()</em> </strong> . It is important to properly manage memory usage when working with dynamic arrays to avoid memory leaks and other memory-related issues.</p> <hr></size;>

Erläuterung:

In diesem Beispiel erstellen wir zunächst ein dynamisches Array arr der Größe 5 Verwendung der malloc()-Funktion . Danach setzen wir jedes Element des Arrays mit a auf seinen Index for-Schleife . Um die Größe des Arrays zu ändern, setzen wir den Wert von size auf 10 und nutzen Sie die realloc() Funktion zum Ändern der Array-Größe. Danach legen wir den Wert der neuen Elemente im Array mithilfe einer weiteren for-Schleife fest. Schließlich drucken wir den Inhalt des Arrays aus und geben den vom Array verwendeten Speicher frei.

Abschluss

Dynamische Arrays sind eine leistungsstarke Datenstruktur in der Programmierung, die die Erstellung und Bearbeitung von Arrays unterschiedlicher Größe zur Laufzeit ermöglicht. In C werden dynamische Arrays mithilfe von Zeigern und Speicherzuweisungsfunktionen implementiert, was sie zu einem wertvollen Werkzeug zur Optimierung der Speichernutzung und zur Erstellung effizienter Programme macht.

Während dynamische Arrays haben viele Vorteile, aber auch einige Nachteile. Dynamische Arrays können komplexer zu implementieren sein als statische Arrays und in manchen Fällen langsamer sein. Die Flexibilität und Effizienz dynamischer Arrays machen sie jedoch zu einem wertvollen Werkzeug für viele Programmieraufgaben.

Um dynamische Arrays in C zu erstellen und zu bearbeiten, müssen wir Speicherzuweisungsfunktionen verwenden, um Speicher während der Laufzeit zuzuweisen und freizugeben. Die am häufigsten verwendeten Speicherzuweisungsfunktionen in C sind malloc() , calloc() , Und realloc() . Bei der Arbeit mit dynamischen Arrays ist es wichtig, die Speichernutzung ordnungsgemäß zu verwalten, um Speicherlecks und andere speicherbezogene Probleme zu vermeiden.

der die Schule geschaffen hat