Dynamically allocating arrays in C
This article will demonstrate various ways to dynamically allocate arrays in C.
malloc
Dynamically allocate arrays in C
using function
malloc
The allocate_by function is the core function for allocating dynamic memory on the heap. It allocates a given number of bytes and returns a pointer to the memory area. Therefore, if you want to dynamically allocate an array of some object type, you should first declare a pointer of that type. Next, you should call it by passing the number of elements multiplied by the size of a single object as a parameter malloc
.
In the following example, we allocate memory to store a character string. As required by secure coding standards, errno
set to 0 and check malloc
the pointer returned by the call to verify successful execution of the function. Finally, memmove
the function is used to copy the string to the allocated memory location.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define SIZE 100
const char *str = "random string to be moved";
int main() {
char *arr = NULL;
errno = 0;
arr = malloc(SIZE * sizeof(char));
if (!arr) {
perror("malloc");
exit(EXIT_FAILURE);
}
memmove(arr, str, strlen(str));
printf("arr: %s\n", arr);
free(arr);
exit(EXIT_SUCCESS);
}
Output:
arr: random string to be moved
Use realloc
the function to modify the allocated memory area in C language
realloc
The getsize() function is used to modify the size of a memory area previously malloc
allocated by realloc
a call to getsize(). It takes the original memory address and the new size as the second argument. Note that it may return the same pointer as passed, or it may return a different pointer depending on the requested size and the available memory after the given address. At the same time, the contents of the previous array will remain unchanged up to the newly specified size.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define SIZE 100
const char *str = "random string to be moved";
int main() {
char *arr = NULL;
errno = 0;
arr = malloc(SIZE);
if (!arr) {
perror("malloc");
exit(EXIT_FAILURE);
}
int num = 102; // User Provided Value
for (int i = 0; i < num; ++i) {
if (i > SIZE) {
arr = realloc(arr, 2 * SIZE);
if (!arr) {
perror("realloc");
exit(EXIT_FAILURE);
}
}
arr[i] = 'a';
}
free(arr);
exit(EXIT_SUCCESS);
}
Using macros to implement array allocation of given objects in C
Typically, malloc
it is used to allocate arrays of some user-defined structures. Since malloc
the returned pointer is void
a pointer and can be implicitly converted to any other type, it is better to explicitly convert the returned pointer to the corresponding type. Because it is easy to miss something and not include the correct markup, we implemented a macro expression that takes the number of elements in the array and the object type to automatically construct the correct malloc
statement, including the correct cast.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define SIZE 100
typedef enum { Jan, Feb, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC} month;
typedef struct {
unsigned char dd;
month mm;
unsigned yy;
} date;
#define MALLOC_ARRAY(number, type) \
((type *)malloc((number) * sizeof(type)))
int main() {
date *d = NULL;
errno = 0;
d = MALLOC_ARRAY(SIZE, date);
if (!d) {
perror("malloc");
exit(EXIT_FAILURE);
}
free(d);
exit(EXIT_SUCCESS);
}
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Flushing stdout output stream in C
Publish Date:2025/04/17 Views:200 Category:C语言
-
stdout This article will demonstrate various methods on how to flush an output stream in C language . Use function in C language fflush to refresh stdout output stream I/O The C standard library provides a stdio buffered version of the I/O
Using the feof function in C language
Publish Date:2025/04/17 Views:87 Category:C语言
-
feof This article will introduce several ways to use functions in C language . Use feof the function to check the end-of-file indicator on a file stream in C language feof The function is part of the C standard input/output library and is d
Use the C language setenv function to access environment variables
Publish Date:2025/04/17 Views:122 Category:C语言
-
setenv This article will introduce several methods of using functions to export environment variables in C language . setenv Use function to export environment variables in C language Every program running on a Unix-base system has an envir
How to get the size of an array in C
Publish Date:2025/04/17 Views:62 Category:C语言
-
This tutorial explains how to determine the length of an array in C. sizeof() The operator is used to get the size/length of an array. sizeof() Operator determines the size of an array in C sizeof() The operator is a compile time unary oper
Initialize array to 0 in C
Publish Date:2025/04/17 Views:133 Category:C语言
-
This article explains how to initialize an array to 0 in C language. The declaration of an array in C language is as follows. char ZEROARRAY[ 1024 ]; It becomes all zeros at runtime in the global scope. If it is a local array, there is a si
Structure arrays in C
Publish Date:2025/04/17 Views:188 Category:C语言
-
This tutorial explains how to create a structure array in C language, which is a collection of multiple structure variables, each of which contains information about a different entity. Structure arrays in C An array is a sequential collect
Printing Character Array in C
Publish Date:2025/04/17 Views:106 Category:C语言
-
This article will introduce various methods on how to print character array in C language. for How to use loop to print character array in C language If we want to print array elements individually and format the output with more details, f
Clearing a character array in C
Publish Date:2025/04/17 Views:119 Category:C语言
-
This article will introduce several methods to clear character arrays in C language. memset Use function to clear char array in C language memset The _set_storage_region function is commonly used to set a storage area to a constant value. T
Initializing character array in C
Publish Date:2025/04/17 Views:92 Category:C语言
-
This article will demonstrate various ways of initializing a character array in C language. {} Initializing a character array in C using curly brace list notation Character arrays are mostly declared as a fixed-size structure and are often