logo

Tablica dynamiczna w C

Tablice dynamiczne to potężna struktura danych w programowaniu, która pozwala na tworzenie I manipulowanie tablice o różnych rozmiarach w czasie wykonywania. W języku C tablice dynamiczne są implementowane przy użyciu wskaźników i funkcji alokacji pamięci, co czyni je cennym narzędziem do optymalizacji wykorzystania pamięci i tworzenia wydajnych programów. W tym artykule omówimy koncepcję tablic dynamicznych w języku C, ich zalety i wady oraz sposoby ich tworzenia i manipulowania nimi.

Zrozumienie tablic dynamicznych

A tablica dynamiczna jest tablicą, której rozmiar można zmieniać w trakcie czas wykonania . w odróżnieniu tablice statyczne , które mają stały rozmiar określany w czasie kompilacji, w razie potrzeby można zmieniać rozmiar tablic dynamicznych. Pozwala na większą elastyczność i lepsze zarządzanie pamięcią, ponieważ rozmiar tablicy można dostosować do ilości przechowywanych danych.

Tablice dynamiczne są implementowane przy użyciu wskaźników i funkcji alokacji pamięci. W języku C najczęściej używanymi funkcjami alokacji pamięci są malloc() , kaloc() , I realloc() . Funkcje te pozwalają na alokację i zwalnianie pamięci w czasie wykonywania, co jest niezbędne do tworzenia tablic dynamicznych i manipulowania nimi.

Zalety tablic dynamicznych

Używanie tablic dynamicznych w C ma kilka zalet. Oto niektóre z głównych zalet:

  1. Jedną z głównych zalet jest to, że pozwalają na lepsze zarządzanie pamięcią. W przypadku tablic statycznych rozmiar tablicy wynosi naprawił , co oznacza, że ​​pamięć jest przydzielana jednocześnie dla całej tablicy. Może to prowadzić do marnowania pamięci, jeśli tablica nie jest w pełni wykorzystana.
  2. W przypadku tablic dynamicznych pamięć jest przydzielana tylko w razie potrzeby, co może prowadzić do bardziej efektywnego wykorzystania pamięci.
  3. Dynamiczne tablice pozwalają również na większą elastyczność.
  4. Może to być ograniczające, zwłaszcza jeśli rozmiar tablicy musi się zmienić w czasie wykonywania.
  5. Tablice dynamiczne umożliwiają dostosowanie rozmiaru tablicy w razie potrzeby, co może sprawić, że programy będą bardziej wszechstronne i elastyczne.

Wady tablic dynamicznych

Tablice dynamiczne mają wiele zalet, ale mają też pewne wady. Niektóre z głównych wad są następujące:

stronniczość i wariancja
  1. Jedną z głównych wad jest to, że ich wdrożenie może być bardziej skomplikowane niż tablice statyczne.
  2. Tablice dynamiczne wymagają użycia wskazówki I funkcje alokacji pamięci , co może być trudniejsze do zrozumienia i użycia niż prosta składnia tablicowa tablic statycznych.
  3. Tablice dynamiczne mogą być również wolniejsze niż tablice statyczne. Ponieważ w grę wchodzi alokacja i dezalokacja pamięci, korzystanie z tablic dynamicznych wiąże się z dodatkowymi kosztami. Ten koszt ogólny może w niektórych przypadkach sprawić, że tablice dynamiczne będą wolniejsze niż tablice statyczne.

Tworzenie tablic dynamicznych w C

Aby utworzyć tablicę dynamiczną w C, musimy użyć funkcje alokacji pamięci aby przydzielić pamięć dla tablicy. Najczęściej używanymi funkcjami alokacji pamięci w C są malloc(), calloc() , I realloc() . Oto przykład tworzenia tablicy dynamicznej za pomocą malloc():

Java sortowanie listy tablic
 int *arr; int size = 10; arr = (int*) malloc(size * sizeof(int)); 

Wyjaśnienie:

W tym przykładzie deklarujemy wskaźnik do tablicy liczb całkowitych o nazwie przyr . Deklarujemy również zmienną całkowitą o nazwie rozmiar , który reprezentuje rozmiar tablicy, którą chcemy utworzyć. Następnie używamy malloc() funkcja przydzielająca pamięć dla tablicy. The malloc() funkcja przyjmuje rozmiar tablicy (w bajty ) jako argument, więc mnożymy rozmiar tablicy przez rozmiar liczby całkowitej (tj 4 bajty w większości systemów), aby uzyskać całkowity rozmiar w bajtach.

Manipulowanie tablicami dynamicznymi w C

Kiedy utworzymy tablicę dynamiczną w C, możemy nią manipulować tak samo jak każdą inną tablicą. Dostęp do poszczególnych elementów tablicy możemy uzyskać za pomocą składni tablicy:

 arr[0] = 5; 

W tym przykładzie ustawiamy pierwszy element tablicy na 5 .

Możemy również skorzystać pętle iterować po tablicy:

 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;>

W tym przykładzie deklarujemy nową zmienną całkowitą o nazwie nowy_rozmiar , który reprezentuje nowy rozmiar tablicy. Następnie używamy funkcja realloc(). aby zmienić rozmiar tablicy. The funkcja realloc(). przenosi wskaźnik do oryginalnego bloku pamięci (w tym przypadku przyr ) i nowy rozmiar bloku pamięci (w bajty ). Mnożymy nowy rozmiar tablicy przez rozmiar z liczba całkowita aby uzyskać całkowity rozmiar w bajtach.

Należy zauważyć, że kiedy zmieniamy rozmiar tablicy dynamicznej za pomocą realloc() , wszelkie istniejące dane w tablicy zostaną zachowane. Jeżeli nowy rozmiar tablicy będzie większy od rozmiaru pierwotnego, nowe elementy nie zostaną zainicjowane.

Aby zwolnić pamięć używaną przez tablicę dynamiczną w C, możemy użyć metody bezpłatny() funkcjonować. The bezpłatny() funkcja pobiera wskaźnik do bloku pamięci, który został przydzielony za pomocą malloc() , kaloc() , Lub realloc() . Oto przykład zwolnienia pamięci używanej przez tablicę dynamiczną:

 free(arr); 

W tym przykładzie używamy funkcja free(). aby zwolnić pamięć używaną przez tablicę dynamiczną przyr . Należy pamiętać, że po zwolnieniu pamięci wykorzystywanej przez tablicę dynamiczną nie powinniśmy podejmować prób uzyskiwania dostępu do elementów tablicy.

tablica sortowania Java

Kilka innych przykładów użycia tablic dynamicznych w C:

Dodawanie elementów do tablicy dynamicznej:

Jedną z głównych zalet korzystania z tablicy dynamicznej jest możliwość dodawania elementów do tablicy w razie potrzeby. Oto przykład dodania elementu do tablicy dynamicznej:

 #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;>

Wyjaśnienie:

W tym przykładzie najpierw tworzymy tablicę dynamiczną przyr wielkościowy 5 używając malloc() funkcjonować. Następnie ustawiamy każdy element tablicy na jego indeks za pomocą a dla pętli . Aby dodać nowy element do tablicy, zwiększamy rozmiar tablicy o jeden i używamy metody funkcja realloc(). aby zmienić rozmiar tablicy. Ustawiamy wartość ostatniego elementu tablicy na aktualną wartość I . Na koniec wypisujemy zawartość tablicy i zwalniamy pamięć wykorzystywaną przez tablicę.

Zmiana rozmiaru tablicy dynamicznej

Kolejną zaletą korzystania z tablicy dynamicznej jest możliwość zmiany rozmiaru tablicy w razie potrzeby. Oto przykład zmiany rozmiaru tablicy dynamicznej:

krojenie tablicy Java
 #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;>

Wyjaśnienie:

W tym przykładzie najpierw tworzymy tablicę dynamiczną przyr wielkościowy 5 używając funkcja malloc(). . Następnie ustawiamy każdy element tablicy na jego indeks za pomocą a dla pętli . Aby zmienić rozmiar tablicy, ustawiamy wartość size na 10 i skorzystaj z realloc() funkcja zmiany rozmiaru tablicy. Następnie ustawiamy wartość nowych elementów tablicy za pomocą kolejnej pętli for. Na koniec wypisujemy zawartość tablicy i zwalniamy pamięć wykorzystywaną przez tablicę.

Wniosek

Tablice dynamiczne to potężna struktura danych w programowaniu, która pozwala na tworzenie i manipulowanie tablicami o różnych rozmiarach w czasie wykonywania. W języku C tablice dynamiczne są implementowane przy użyciu wskaźników i funkcji alokacji pamięci, co czyni je cennym narzędziem do optymalizacji wykorzystania pamięci i tworzenia wydajnych programów.

sortuj listę tablic Java

Chwila tablice dynamiczne mają wiele zalet, mają też pewne wady. Tablice dynamiczne mogą być bardziej skomplikowane w implementacji niż tablice statyczne i w niektórych przypadkach mogą być wolniejsze. Jednak elastyczność i wydajność tablic dynamicznych czyni je cennym narzędziem do wielu zadań programistycznych.

Aby tworzyć tablice dynamiczne i nimi manipulować w języku C, musimy używać funkcji alokacji pamięci do alokacji i zwalniania pamięci w czasie wykonywania. Najczęściej używanymi funkcjami alokacji pamięci w C są malloc() , kaloc() , I realloc() . Ważne jest, aby właściwie zarządzać wykorzystaniem pamięci podczas pracy z tablicami dynamicznymi, aby uniknąć wycieków pamięci i innych problemów związanych z pamięcią.