当前位置:网站首页>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.
边栏推荐
- XSS (cross site script attack) summary (II)
- 渗透测试-目录遍历漏洞
- Attack and defense world web baby Web
- Small sample learning data set
- Specific operations for uploading pictures in PHP
- Summary of SQL injection (I)
- Fun CMD command line~
- Cookie & session & JSP (XII)
- In Net 6 using dotnet format formatting code
- Working principle of asemi three-phase rectifier bridge
猜你喜欢

great! Auto like, I use pyautogui!

基于SSH实现的学生成绩管理系统

Example of dynamic programming 3 leetcode 55

How to download and use Xiaobai one click reload on the official website

How do the defi protocols perform under this round of stress test?

Five simple data types of JS

XSS (cross site script attack) summary (II)

Qdebug June 2022

Dynamic programming example 1 leetcode 322 coin change

Specific operations for uploading pictures in PHP
随机推荐
Detailed summary of float
Understand JS high-order function and write a high-order function
Eyeshot 2022 Released
Notes on non replacement elements in the line (padding, margin, and border)
PHP calls map API
Startup mode of SoC verification environment
A review of small sample learning
hr竟主动给这位测试小姐姐涨工资,她是怎么做到的?
February 19 CTF exercise
Integrate CDN to create the ultimate service experience for customers!
How to make colleagues under the same LAN connect to their own MySQL database
Redis (17)
Fun CMD command line~
ThinkPHP 5 log management
《QDebug 2022年6月》
Detailed summary of position positioning
epplus复制模板后打印区域变小的问题
Keyboard key code value
How to choose the years of investment in financial products?
Edge loss 解读