当前位置:网站首页>Fundamentals of C language
Fundamentals of C language
2022-06-25 05:15:00 【Jornhitom】
Array
It is often useful to think of an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest to the last element.
Declaring Arrays
- the type of the elements
- number of elements
type_name array_name[array_size];
For example:
double balance[10];
Initializing Arrays
Initializing an array using a single statement:
double balance[5] = {
1000.0, 2.0, 3.4, 7.0, 50.0};
If you omit the size of the array, an array just big enough to hold the initialization is created:
double balance[] = {
1000.0, 2.0, 3.4, 7.0, 50.0};
You created exactly the same array as you did in the previous example
Pointers
Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers.
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before using it to store any variable address.
char *character_pointer;
Here, char is the pointer’s base type.
Pointers and Arrays
In the coming example, I demonstrate how you can declare an array of strings by using pointer syntax and array syntax together.
#define MAX_LINE_LENGTH 512
#define MAX_ARGV_LENGTH (MAX_LINE_LENGTH / 2 + 1)
char* command_args[MAX_ARGV_LENGTH];
Here, I create an array of type char* and of size MAX_ARGV_LENGTH. Since a char* is how to represent a string in C, this line of code above will declare an array of strings whose length is 257.
Dynamic Memory Allocation
C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.
There are 4 functions under <stdlib.h> to facilitate dynamic memory allocation:malloc()calloc()free()realloc()
malloc() or memory allocation
It is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with default garbage value.
Syntax: ptr = (cast_type*) malloc(size_in_byte)
For example: ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
If space is insufficient, allocation fails and returns a NULL pointer.
calloc() or contiguous allocation
It is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default “zero value”.
Syntax: ptr = (cast_type*) calloc(number_of_element, element_size)
For example: ptr = (float*) calloc(25, sizeof(float));
If space is insufficient, allocation fails and returns a NULL pointer.
free() method
The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax: free(ptr)
realloc() or re-allocation
It is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value.
Syntax: ptr = realloc(ptr, new_size);
where ptr is reallocated with new size new_size.
Note: It would be better to use
mallocovercalloc, unless we want the zero-initialization becausemallocis faster thancalloc.
Call by Reference
Pointers and Reference
Here, I will use C++ to demonstrate the concepts instead of use C.
// pass parameters by pointers
void swap(int* x, int*y) {
int z = *x;
*x = *y;
*y = z;
}
int main() {
int a = 1;
int b = 2;
swap(&a, &b);
return 0;
}
Now, let’s see what happened when we pass parameters by references.
// pass parameters by references
void swap(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int a = 1;
int b = 2;
swap(a, b);
return 0;
}
Key Differences in Reference Variable and Pointer Variable
- Since references can’t be
NULL, they are safer to use. - A pointer can be reassigned while a reference can’t be. A reference must be assigned at initialization only while a pointer can be assigned to a value after its initialization.
- A pointer to a class/struct uses
->operator to access its members whereas a reference to a class/struct uses.operator. - A pointer needs to be dereferenced with
*to access the memory location whereas a reference can be used directly.
边栏推荐
- Detailed summary of float
- great! Auto like, I use pyautogui!
- CopyPlugin Invalid Options options should be array ValidationError: CopyPlugin Invalid Options
- Enhanced paste quill editor
- Native JS high risk reminder pop-up code snippet, "are you sure you want to do this?" and "it cannot be recovered after deletion. Do you want to continue“
- Edge loss interpretation
- epplus复制模板后打印区域变小的问题
- DOM document object model (I)
- Wechat applet new version prompt update
- ThinkPHP 5 log management
猜你喜欢

DOM document object model (I)

Web3 DAPP user experience best practices

CSRF (Cross Site Request Forgery) &ssrf (server request forgery) (IV)

Compatible with Internet Explorer

Baidu ueeditor set toolbar initial value

2021-03-23

Penetration test - right raising topic

Attack and defense world web baby Web

buuctf(re)

Personalized Federated Learning with Moreau Envelopes
随机推荐
In Net 6 using dotnet format formatting code
Could not find “store“ in the context of “Connect(homePage)
Handwritten promise all
Summary of SQL injection (I)
Create an environment for new projects
Click to jump out and drag the pop-up window
WPF uses Maui's self drawing logic
A brief talk on media inquiry
ORA-00800: soft external error
Filter & listener (XIV)
Laravel Aurora push
Prototypical Networks for Few-shot Learning
A summary of the experiment of continue and break in C language
CTFHUB SSRF
Characteristics of ES6 arrow function
Drag modal box
Attack and defense world web baby Web
2021-03-23
PHP uses JWT
Virtual honeypot Honeyd installation and deployment