Hello everyone! , I have been preparing for the mathematical modeling competition some time ago, and now I am finished. Hurry up and continue to bring you C language content. Today I will give you an explanation of the basic part of pointers.
When we talk about pointers in C language, we are actually discussing a very important concept, because pointers are one of the core of C language. They allow us to directly access data in memory, which is very useful when writing efficient and flexible programs. Let’s take a deeper look at the concept and usage of pointers
Table of contents
1. Preliminary understanding of pointers
3. The meaning of pointer types
①The pointer is not initialized
② Pointer out-of-bounds access
③Release the space pointed by the pointer
3. Relational operations on pointers
1. What is a pointer?
1. Preliminary understanding of pointers
Two key points to understand pointers:1. A pointer is the number of a smallest unit in memory, that is, the address.2. The pointers mentioned in normal spoken language usually refer to pointer variables, which are variables used to store memory addresses.Summary: Pointers are addresses. Pointers in spoken language usually refer to pointer variables.
Pointer variable:We can use & (address operator) to get the actual memory address of the variable, and store the address in a variable. This variable is a pointer variable.
#include<stdio.h>
int main()
{
int a = 7;//创建变量时,在内存里开辟的一篇空间
int* pa = &a;//这里我们对变量a,取出它的地址,可以使用&操作符
//a变量占用4个字节的空间,这里是将a的4个字节的第一个字节的地址存放在p变量
//中,p就是一个之指针变量
return 0;
}
Summary: Pointer variables are variables used to store addresses. (The values stored in pointers are treated as addresses)
2. The size of the pointer
In C language, the size of pointers varies depending on the computer architecture and operating system. Typically, the size of a pointer is related to the number of bits in the computer. In 32-bit systems, the pointer size is usually 4 bytes (32-bit), while in 64-bit systems, the pointer size is usually 8 bytes (64-bit)
3. Summary
- Pointers are used to store addresses, and addresses uniquely identify an address space.
- The size of the pointer is 4 bytes on 32 -bit platforms and 8 bytes on 64 -bit platforms.
2. Pointers and pointer types
Variables have different types, integer, floating point, etc. Does the pointer have a type?
Pointers do have:
char *pc = NULL;
int *pi = NULL;
short *ps = NULL;
long *pl = NULL;
float *pf = NULL;
double *pd = NULL;
As you can see here, the definition of pointers is: type + * .actually:A pointer of type char* is used to store the address of a variable of type char .The short* type pointer is used to store the address of the short type variable.The pointer of type int* is used to store the address of the variable of type int
Next, explore the meaning of pointer types
3. The meaning of pointer types
The type of the pointer determines how much authority you have when dereferencing the pointer (how many bytes can be manipulated)
For example: char* pointer dereference can only access one byte, while int* pointer dereference can access four bytes.
1. Pointer + - integer
int main()
{
int n = 10;
char* pc = (char*)&n;
int* pi = &n;
printf("%p\n", &n);
printf("%p\n", pc);
printf("%p\n", pc + 1);
printf("%p\n", pi);
printf("%p\n", pi + 1);
return 0;
}
2.Dereference
It can be seen that the values of pc and pi are equal. After running *pc=0, only the value of the first byte is changed.
After running *p=0, only the value of four bytes is changed.
4. Wild pointer
Concept: A wild pointer means that the position pointed by the pointer is unknown (random, incorrect, and without clear restrictions)
1. Causes of wild pointers
①The pointer is not initialized
int main()
{
int* pa;
*pa = 10;
return 0;
}
Even the compiler prevents us from using uninitialized pointers
② Pointer out-of-bounds access
int main()
{
int arr[10] = { 0 };
int* p = arr;
for (int i = 0; i <= 11; i++)
{
*(p++) = i;
}
return 0;
}
When the range pointed by the pointer exceeds the range of the array arr , p is a wild pointer: an error will naturally be reported.
③Release the space pointed by the pointer
int* createInt() {
int num = 5;
int* ptr = #
return ptr;
}
int main() {
int* ptr = createInt();
printf("%d\n", *ptr); // 输出5,但是这是不安全的操作
// 在这之后,ptr成为了野指针,因为它指向的内存空间已经被释放
printf("%d\n", *ptr); // 未定义的行为,可能输出垃圾值或导致程序崩溃
return 0;
}
In the above example, the function
createInt()
creates an integer variablenum
, assigns its address to a pointerptr
, and returns the pointer. Inmain()
the function, we printptr
the value pointed to by the pointer, and the output is 5. ButcreateInt()
after the function ends,num
the life cycle of the variable ends and the memory space it occupies is released. At this time, the pointerptr
still retains the previous memory address and becomes a wild pointer. In subsequent print operations, we try to accessptr
the value pointed to by the wild pointer. This is an unsafe operation and may lead to undefined behavior of the program.
5. Pointer arithmetic
1. Pointer + - integer
- Pointer addition and subtraction of integers refers to the addition and subtraction of pointers, where the integer represents the offset to be added or subtracted. This operation is typically used to move a pointer a certain distance in order to access the memory location pointed to by the pointer
- Pointer addition and subtraction operations are based on the size of the data type pointed to by the pointer. For example, if a pointer points to a
int
variable of one type, then adding 1 to the pointer will make the pointer point to aint
variable of the next type. Similarly, decrementing the pointer by 1 will make the pointer point to aint
variable of the previous type.
#include<stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5 };
int* pa = arr;
for (int i = 0; i < 5; i++)
{
printf("%d ", *(pa++));
}
return 0;
}
2. Pointer - pointer
Pointer-pointer operation refers to subtracting two pointers to obtain the offset between them. This operation is usually used to calculate the distance between two pointers or the number of elements.
Next we can use this to simulate and implement the strlen() function
int my_strlen(char* pa)
{
char* start = pa;
while (*pa)
{
pa++;
}
return pa - start;
}
int main()
{
char arr[] = "hello";
printf("%d", my_strlen(arr));
return 0;
}
3. Relational operations on pointers
==
: Determine whether two pointers are equal. If two pointers point to the same memory address, they are equal and returned1
; otherwise, returned0
.!=
: Determine whether two pointers are not equal. If the two pointers point to different memory addresses, they are not equal and return1
; otherwise, return0
.>
: Determine whether one pointer is greater than another pointer. The size of the pointer is compared based on the memory address pointed by the pointer. If the address pointed by the first pointer is after the address pointed by the second pointer, then the first pointer is greater than the second pointer, return1
; otherwise, return0
.<
: Determine whether one pointer is smaller than another pointer. The size of the pointer is compared based on the memory address pointed by the pointer. If the address pointed by the first pointer is before the address pointed by the second pointer, then the first pointer is smaller than the second pointer, return1
; otherwise, return0
.>=
: Determine whether a pointer is greater than or equal to another pointer. Returns if the first pointer is greater than the second pointer or if the two pointers are equal1
; otherwise0
.<=
: Determine whether a pointer is less than or equal to another pointer. Returns if the first pointer is less than the second pointer or if the two pointers are equal; otherwise,1
returns0
4.Attention
A pointer to an array element is allowed to be compared with a pointer to a memory location after the last element of the array, but not to a pointer to a memory location before the first element.
6. Pointers and arrays
1. A pointer is a variable used to store a memory address. Pointer variables can point to any type of data, including arrays. Through pointers, we can indirectly access and manipulate data in memory.
2. An array is an array, which can store a set of numbers. The size of the array depends on the type and number of elements.
3. The array name of the array is the address of the first element of the array, and the address can be placed in a pointer variable. Accessing elements of an array through pointers
- Array name and pointer: In C language, the array name can be regarded as a pointer to the first element of the array. For example, for an array
int arr[5]
,arr
it can be thought of asarr[0]
a pointer to. Therefore, you can access the elements in the array through pointers, such as*arr
the first element of the array and*(arr + 1)
the second element of the array. - Additionally, pointer arithmetic operations can also be applied to array names. For example,
arr + 1
represents the address of the second element of the array,arr + 2
represents the address of the third element of the array. This is because the elements of the array are stored contiguously in memory.
int main()
{
int arr[] = { 1,2 };
int* pa = arr;
printf("%p\n", arr);
printf("%p\n", &arr[0]);
return 0;
}
It can be seen that the array name usually represents the address of the first element of the array, but there are two exceptions:
1. sizeof (array name), the array name is placed alone inside sizeof, the array name represents the entire array, and the size of the array is calculated, in words. Festival.
2.&Array name, the array name represents the entire array, and the address of the array is taken out. The address of the array is the same as the address of the first element of the array, but the type and meaning are different.
7. Secondary pointer
Pointer variables are also variables. Variables have addresses. So where is the address of the pointer variable stored?
This is the secondary pointer
int main()
{
int a = 10;
int* pa = &a;//一级指针
int** ppa = &pa;//二级指针
printf("%d\n", a);
**ppa = 0;//通过两次解引用来改变值
printf("%d\n", a);
return 0;
}
8. Pointer array
A pointer array is an array, an array that stores pointers.
You can use an array of pointers to simulate a two-dimensional array
int main()
{
int arr1[] = { 1,2,4,6 };
int arr2[] = { 7,2,4,4 };
int arr3[] = { 1,2,9,6 };
int* p[] = { arr1,arr2,arr3 };
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d ", p[i][j]);
}
printf("\n");
}
return 0;
}
Pointers are a powerful and complex concept in C language. By using pointers, we can directly access and modify data in memory, achieving flexible and efficient memory operations. However, you need to be careful when using pointers to avoid null and wild pointer problems. I hope this article will help you understand the pointer part of C language.