MMGameslogo  MMGames
TwitterSharebutton  FacebookSharebutton   
learn through sufferingC Language
learn through sufferingC Language

I want to use dynamic arrays and malloc.

I want to declare a dynamic array using malloc, but I don't know how.
"First, you don't need malloc in programs written by beginners."
Modern computers won't even flinch at an array like char s[1000000];.
Also, in embedded systems, it's the opposite—malloc should be avoided as well, for memory conservation.
Taking that into consideration, please read the following usage.

Allocate memory as follows:It's the same for data types other than int.even with structs.
int *data;
data = malloc(sizeof(int) * required_number_of_elements);

The allocated memory can be used just like a regular array.
data[i] = 10;

If you want to increase the number of elements, do it like this.
data = realloc(data, sizeof(int) * required_element_count);

"If you no longer use the array, free it like this."
free(p);

However, if the program is very small, it's not necessary to deallocate memory using the free function.
Forgetting to release resources in large programs can lead to what's known as a "memory leak," where memory usage gradually increases over time.
Therefore, to cultivate the habit of releasing resources, always call the free function.


About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.

Part 0: Program Overview
  1. What is a program?
Chapter 3: Displaying on the Screen
  1. String Display
  2. newline character
  3. Practice Problem 3
Chapter 4: Displaying and Calculating Numbers
  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4
Chapter 6: Input from the Keyboard
  1. input function
  2. The fear of input
  3. Practice Problem 6
Chapter 9: Repeating a Fixed Number of Times
  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9
Chapter 10: Repeating Without Knowing the Number of Times
  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10
Chapter 13: Handling Multiple Variables at Once
  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13
Chapter 19: Dynamic Arrays
  1. Create arrays freely.
  2. Practice Problem 19