logo

Dynamic Array i C

Dynamiske arrays er en kraftig datastruktur i programmering som gir rom for skaper og manipulere arrays av varierende størrelse under kjøring. I C implementeres dynamiske arrays ved hjelp av pekere og minneallokeringsfunksjoner, noe som gjør dem til et verdifullt verktøy for å optimalisere minnebruk og lage effektive programmer. I denne artikkelen vil vi utforske konseptet med dynamiske arrays i C, deres fordeler og ulemper, og hvordan man lager og manipulerer dem.

Forstå dynamiske matriser

EN dynamisk array er en matrise hvis størrelse kan endres under kjøretid . I motsetning til statiske arrays , som har en fast størrelse som bestemmes på kompileringstidspunktet, kan dynamiske matriser endres etter behov. Det gir mer fleksibilitet og bedre minnehåndtering, ettersom størrelsen på arrayet kan justeres for å passe mengden data som lagres.

Dynamiske arrays implementeres ved hjelp av pekere og minneallokeringsfunksjoner. I C er de mest brukte minneallokeringsfunksjonene malloc() , calloc() , og realloc() . Disse funksjonene tillater allokering og deallokering av minne under kjøring, noe som er nødvendig for å lage og manipulere dynamiske arrays.

Fordeler med Dynamic Arrays

Det er flere fordeler ved å bruke dynamiske matriser i C. Noen av hovedfordelene er som følger:

  1. En av hovedfordelene er at de gir bedre minnehåndtering. Med statiske matriser er størrelsen på matrisen fikset , som betyr at minne tildeles for hele matrisen samtidig. Det kan føre til bortkastet minne hvis arrayet ikke utnyttes fullt ut.
  2. Med dynamiske matriser tildeles minne kun etter behov, noe som kan føre til mer effektiv minnebruk.
  3. Dynamiske arrays gir også større fleksibilitet.
  4. Det kan være begrensende, spesielt hvis størrelsen på matrisen må endres under kjøring.
  5. Dynamiske arrays gjør det mulig å justere størrelsen på arrayen etter behov, noe som kan gjøre programmer mer allsidige og tilpasningsdyktige.

Ulemper med Dynamic Arrays

Mens dynamiske arrays har mange fordeler, har de også noen ulemper. Noen av de største ulempene er som følger:

javascript onload script
  1. En av de største ulempene er at de kan være mer komplekse å implementere enn statiske arrays.
  2. Dynamiske arrays krever bruk av pekere og minnetildelingsfunksjoner , som kan være vanskeligere å forstå og bruke enn den enkle array-syntaksen til statiske arrays.
  3. Dynamiske matriser kan også være tregere enn statiske matriser. Fordi minneallokering og deallokering er involvert, er det en overheadkostnad forbundet med å bruke dynamiske matriser. Denne overheadkostnaden kan gjøre dynamiske matriser tregere enn statiske matriser i noen tilfeller.

Opprette dynamiske matriser i C

For å lage en dynamisk matrise i C, må vi bruke minnetildelingsfunksjoner for å tildele minne for matrisen. De mest brukte minneallokeringsfunksjonene i C er malloc(), calloc() , og realloc() . Her er et eksempel på hvordan du lager en dynamisk matrise ved å bruke malloc():

'abc' er i tall'
 int *arr; int size = 10; arr = (int*) malloc(size * sizeof(int)); 

Forklaring:

I dette eksemplet erklærer vi en peker til en heltallsmatrise kalt arr . Vi erklærer også en heltallsvariabel kalt størrelse , som representerer størrelsen på matrisen vi ønsker å lage. Etter det bruker vi malloc() funksjon for å tildele minne for matrisen. De malloc() funksjonen tar størrelsen på matrisen (in bytes ) som argument, så vi multipliserer størrelsen på matrisen med størrelsen på et heltall (som er 4 byte på de fleste systemer) for å få den totale størrelsen i byte.

Manipulere dynamiske matriser i C

Når vi har laget en dynamisk matrise i C, kan vi manipulere den akkurat som en hvilken som helst annen matrise. Vi kan få tilgang til individuelle elementer i matrisen ved å bruke matrisesyntaks:

 arr[0] = 5; 

I dette eksemplet setter vi det første elementet i matrisen til 5 .

Vi kan også bruke løkker å iterere over matrisen:

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

I dette eksemplet erklærer vi en ny heltallsvariabel kalt ny_størrelse , som representerer den nye størrelsen på matrisen. Etter det bruker vi realloc() funksjon for å endre størrelsen på matrisen. De realloc() funksjon tar pekeren til den opprinnelige minneblokken (i dette tilfellet, arr ) og ny størrelse av minneblokken (i bytes ). Vi multipliserer ny størrelse av matrisen av størrelse av en heltall for å få den totale størrelsen i byte.

Det er viktig å merke seg at når vi endrer størrelsen på en dynamisk matrise ved hjelp av realloc() , vil alle eksisterende data i arrayet bli bevart. Hvis den nye størrelsen på matrisen er større enn den opprinnelige størrelsen, vil de nye elementene ikke initialiseres.

For å frigjøre minnet som brukes av en dynamisk matrise i C, kan vi bruke gratis() funksjon. De gratis() funksjonen tar en peker til minneblokken som ble tildelt ved hjelp av malloc() , calloc() , eller realloc() . Her er et eksempel på hvordan du frigjør minnet som brukes av en dynamisk matrise:

fmovies india
 free(arr); 

I dette eksemplet bruker vi free() funksjon for å frigjøre minnet som brukes av den dynamiske matrisen arr . Det er viktig å merke seg at når vi har frigjort minnet som brukes av en dynamisk matrise, bør vi ikke forsøke å få tilgang til elementene i matrisen.

Noen flere eksempler på bruk av dynamiske matriser i C:

Legge til elementer i en dynamisk matrise:

blokkerte numre

En av hovedfordelene med å bruke en dynamisk matrise er muligheten til å legge til elementer i matrisen etter behov. Her er et eksempel på hvordan du legger til et element i en dynamisk matrise:

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

Forklaring:

I dette eksemplet lager vi først en dynamisk matrise arr av størrelse 5 bruker malloc() funksjon. Etter det setter vi hvert element i matrisen til sin indeks ved å bruke en for løkke . For å legge til et nytt element til matrisen, øker vi størrelsen på matrisen med én og bruker realloc() funksjon for å endre størrelsen på matrisen. Vi setter verdien av det siste elementet i matrisen til gjeldende verdi av Jeg . Til slutt skriver vi ut innholdet i matrisen og frigjør minnet som brukes av matrisen.

Endre størrelsen på en dynamisk matrise

En annen fordel med å bruke en dynamisk matrise er muligheten til å endre størrelsen på matrisen etter behov. Her er et eksempel på hvordan du endrer størrelsen på en dynamisk matrise:

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

Forklaring:

I dette eksemplet lager vi først en dynamisk matrise arr av størrelse 5 bruker malloc() funksjon . Etter det setter vi hvert element i matrisen til sin indeks ved å bruke en for løkke . For å endre størrelsen på matrisen setter vi verdien av størrelse til 10 og bruk realloc() funksjon for å endre størrelsen på matrisen. Etter det setter vi verdien til de nye elementene i matrisen ved å bruke en annen for loop. Til slutt skriver vi ut innholdet i matrisen og frigjør minnet som brukes av matrisen.

Konklusjon

Dynamiske arrays er en kraftig datastruktur i programmering som gjør det mulig å lage og manipulere arrays av varierende størrelse under kjøring. I C implementeres dynamiske arrays ved hjelp av pekere og minneallokeringsfunksjoner, noe som gjør dem til et verdifullt verktøy for å optimalisere minnebruk og lage effektive programmer.

Samtidig som dynamiske matriser har mange fordeler, de har også noen ulemper. Dynamiske arrays kan være mer komplekse å implementere enn statiske arrays og kan være tregere i noen tilfeller. Fleksibiliteten og effektiviteten til dynamiske matriser gjør dem imidlertid til et verdifullt verktøy for mange programmeringsoppgaver.

konverter int til streng

For å lage og manipulere dynamiske matriser i C, må vi bruke minneallokeringsfunksjoner for å tildele og deallokere minne under kjøring. De mest brukte minneallokeringsfunksjonene i C er malloc() , calloc() , og realloc() . Det er viktig å administrere minnebruken på riktig måte når du arbeider med dynamiske matriser for å unngå minnelekkasjer og andre minnerelaterte problemer.