当前位置:网站首页>Get the C language pointer in one article

Get the C language pointer in one article

2022-07-23 09:38:00 LuZhouShiLi

One article C Language pointer

One 、 Memory Overview

1.1 Relevant concepts

  • Memory : In the composition of the computer , Used to store programs and data , auxiliary CPU An important part of arithmetic processing
  • Memory : Internal memory , Temporary program / data , Power loss
  • External storage : External memory , Secondary storage , Don't lose power

Memory is communication CPU Bridge with hard disk

  • Temporary storage CPU Operation data in
  • Temporarily store data exchanged with external memory such as hard disk

1.2 Physical memory and storage address space

  • Physical memory : The actual memory chip

    • The memory module installed on the motherboard
    • The display on the display card RAM chip
    • On various adapter cards RAM Chips and ROM chip
  • Store address space : The range of memory encoding , The memory we often say in software refers to this layer of meaning .

    • code : For each physical storage unit ( A byte ) Assign a number
    • Addressing : The corresponding storage unit can be found according to the assigned number , Complete data reading and writing

1.3 Memory address

  • Abstract the memory into a large one-dimensional character array
  • Coding is about memory Every byte Allocate one 32 For or 64 The number of bits ( This has something to do with the processor )
  • This memory number we call memory address , Each data in memory is assigned a corresponding address
  • char: Allocate an address per byte
  • int: Occupy four bytes and allocate four addresses

Two 、 Pointers and pointer variables

2.1 Popular understanding of pointer

  Start a program , The system allocates a piece of memory space to the program in memory , We programmers only need to focus on logical addresses , This memory space is composed of bytes , Every byte has its address number ( Hexadecimal representation ), such as 32 Bit CPU, Memory addressing is 0x0000 0000 - 0xffff ffff

 Insert picture description here

that , Memory address is actually the number of memory , Let's number this ( Address ) It is called pointer

The pointer == Address == Number

2.2 Pointer to the variable

Pointer to the variable : The variable that holds the pointer , meanwhile , Because the address number is 0x0000 0000, therefore , Pointer variables can be stored in four bytes

If it is 64 Bit compiler , The number range of memory is 0x0000 0000 0000 0000 - 0xffff ffff ffff ffff, Such a number , It takes eight bytes to store , So pointer variables also need eight bytes

2.3 summary

  • Each byte of the memory area has a number , This is the address
  • If a variable is defined in the program , When compiling or running a program , The system will allocate a memory unit to this variable , And determine the memory address
  • The essence of a pointer is a memory address , The pointer is the address , The address is the pointer
  • The pointer is the number of the memory unit , A pointer variable is a variable that holds an address
  • In general, we describe pointer variables as pointers , But the meaning is different .

3、 ... and 、 Definition and initialization of pointer variables

int a = 10;
int *p;
p = &a;
  • Three steps to define pointers

    • * Combined with the symbol, it represents a pointer variable
    • Whose address do you want to save , Put his definition form here
    • use *p Replace the defined variable
  • understand :

    • p And * The combination represents that this is a pointer variable
    • p It's a pointer variable ,p The type is int *( All parts except variable names )
    • Pointer to the variable p For preservation int Type of address ( Remove variable names and recent * Outside part )

about int **p The understanding of the :

  • p It's a pointer variable ,p The type is int **
  • Pointer to the variable p For preservation int * Address of data type ( So it's a two-level pointer )

Four 、 Use of the pointer

*p = 100; //* And p Combination represents : take p The content of the space pointed to by the pointer . Direct assignment here 100

// Modify the value of the variable indirectly through the pointer variable

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    
	int a = 10;
	int* p = &a;

	*p = 100;
	printf("%d\n",a);// a The value of has changed 
	return 0;
}


Be careful :& You can get the address of a variable in memory , But you can't go to register variables , Because register variables are not in memory , And in the CPU in , So there is no address .

When use , Take... For an expression , Will subtract one level from the expression , If you take... For the expression &, Will increase one level **

int *p;
int **q;

q = &p;//  The secondary pointer   Deposit is p The address of 

// q  type  int **
// p  type  int *
//  take &  Add one level *

*q = p;
//  take *  Minus one level 

Four 、 The size of the pointer variable

No matter what type of pointer variable , The size is related to the compiler type ,32 Bit four bytes ,64 Bit eight bytes

5、 ... and 、 The width and step size of the pointer

 Insert picture description here

 Insert picture description here

adopt * When taking the content of the space pointed to by the pointer variable , Getting the width of memory is related to the type of pointer variable itself

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    
	int num = 0x01020304;
	char* p1 = (char*)&num;//int *  Coercive transformation 
	short* p2 = (short*)&num;
	int* p3 = &num;

	//  adopt * When taking the content of the space pointed to by the pointer variable , The width of the memory taken is related to the type of the pointer variable itself 
	printf("%x\n",*p1);//  Only one byte can be taken   Print 04
	printf("%x\n",*p2);// Take two bytes  0403
	printf("%x\n",*p3);//  Take four bytes  01020304

	return 0;
}

The width of the pointer = Match the pointer variable to the nearest pointer variable * Drag black , The rest of the types .

char *p  1
short *p  2
int *p  4
int **p  sizeof(int *)   4
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    
	int num = 0x01020304;
	char* p1 = (char*)&num;//int *  Coercive transformation 
	short* p2 = (short*)&num;
	int* p3 = &num;

	//  adopt * When taking the content of the space pointed to by the pointer variable , The width of the memory taken is related to the type of the pointer variable itself 
	printf("%x\n",*p1);//  Only one byte can be taken   Print 04
	printf("%x\n",*p2);// Take two bytes  0403
	printf("%x\n",*p3);//  Take four bytes  01020304


	printf("%u\n",p1);
	printf("%u\n", p2);
	printf("%u\n", p3);


	printf("%u\n", p1 + 1);//  Add one 
	printf("%u\n", p2 + 1);//  Add 2
	printf("%u\n", p3 + 1);//  Add  4

	return 0;
}

6、 ... and 、 Wild pointer

int *p;

*p = 200;

  A wild pointer is a pointer that is not initialized , The direction of the pointer is random , You cannot manipulate the wild pointer . The pointer p The saved address must be defined ( Applied to the system )

7、 ... and 、 Null pointer

The function of null pointer : If you finish using the pointer, assign the pointer to NULL, Judge whether the pointer is NULL, Know whether the pointer has been used .

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    
	int a;
	//  Assign the value of the pointer to 0,0x000000 = NULL
	int* p = NULL;//  Give the pointer p The content of is assigned to 0
	*p = 200;
	printf("%d\n",*p);
	return 0;
}

8、 ... and 、 Universal pointer

  • void b; You can't define void Variable of type Because the compiler doesn't know how many bytes to allocate to variables
  • But it can be defined as void * type Because the pointer must be four bytes
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    
	int a = 10;
	void* p = (void*)&a;//  Universal pointer can save   Any address   But pointer type conversion is required  
	// printf("%d\n",*p);//  Can't print   because sizeof(void)  I don't know how many bytes   There is no way to get the content in the address 
	printf("%d\n",*(int *)p);//  First convert the pointer type to the original type   Getting content 
	return 0;
}

Nine 、const Decorated pointer variable

  • const Modifier constant You cannot directly modify the content , It needs to be modified by pointer

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	const int a = 10;//  Modifying variables a  No more passing a modify a What's in memory 
	int *p = &a;
	*p = 100;//  You can use the pointer p Modify the content 
	printf("%d\n",*p);
	printf("%d\n",a);
	return 0;
}


* const int *p = &a; Cannot pass *p  To modify the P What it points to 

*p = 100;// error


* int* const p = &a; p The saved address cannot be modified 

p = &b;// error p The value of itself cannot be modified 

* const int *const p = &a;// p The address pointed to by itself cannot be changed    It can't pass *p modify p The address pointed to saves the content 

Ten 、 Multi level pointer

The secondary pointer stores the address of the primary pointer
 Insert picture description here

int *p = &a;

int **q = &p;//  The secondary pointer 

//  If * and & meet , Counteract 
// **q == *(*q) == *(p) == a

11、 ... and 、 Pointers and arrays

11.1 Manipulate array elements through pointers

Pointer plus one , Across an element


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	int a[10] = {
    1,2,3,4,5,6,7,8,9,10};
	// a  Array name , The address of the first element 

	int* p = a;//  The pointer p Save the address of the first element 
	for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
	{
    
		printf("%d ",*(p + i));
	}

	return 0;
}

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	int a[10] = {
    1,2,3,4,5,6,7,8,9,10};
	// a  Array name , The address of the first element 

	int* p = a;//  The pointer p Save the address of the first element 
	for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
	{
    
		*(p + i) = i;
		printf("%d ",*(p + i));
	}

	return 0;
}

11.2 Pointer arithmetic

Subtraction of two pointers , Get how many elements are crossed in the middle , There is no point in adding two pointers


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	int a[10] = {
    1,2,3,4,5,6,7,8,9,10};
	// a  Array name , The address of the first element 
	int* p = a;
	// int* q = &a[9];
	//  We must change here int *  Because add one or subtract one   Will span the entire array of elements 
	//  After the transformation   Just across an element size address 
	int* q = (int*)(&a + 1) - 1;//  Point to last element 
	printf("%d\n",q - p);// 9
	printf("%d\n", *(p + 3));
	return 0;
}

11.3 [] Not exclusive to arrays

a[i] = p[i] = *(p + i) = *(a + i)


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	int a[10] = {
    1,2,3,4,5,6,7,8,9,10};
	int* p = a;

	for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
	{
    
		//printf("%d ",*(a + i));
		//printf("%d ",*(p + i));
		printf("%d ",p[i]);

	}

	return 0;
}

Twelve 、 Pointer array

 Insert picture description here


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	int a = 10;
	int b = 20;
	int c = 30;

	//  Pointer array : Every element in the array is a pointer ( Address )
	int* num[3] = {
    &a,&b,&c};
	printf("%d \n",sizeof(num));

	//  Print a b c
	for (int i = 0; i < sizeof(num) / sizeof(num[0]); i++)
	{
    
		printf("%d ",*num[i]);
	}

	//  Define a pointer to hold the array num The address of the first element 
	//  First num The first element itself is a pointer ( Address )
	// Num = &num[0] = &(int *) = int **
	int** k = num;//  The second level pointer manipulates the pointer array 

	//  Print the elements in the array , Like printing b  Then first pass k Go to the first element address  k + 1 obtain b The address of , after *(k + 1)  obtain num[1] The content of , Last **(k+ 1) obtain b
	for (int i = 0; i < sizeof(num) / sizeof(num[0]); i++)
	{
    
		printf("%d ", **(k + i));//  Manipulate the pointer array through the secondary pointer 
	}

	return 0;
}

13、 ... and 、 Pointer as parameter

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS

void swap(int* x, int* y)
{
    
	//  The incoming address is   Formal parameters can be written in the form of pointers 
	int k = *x;
	*x = *y;
	*y = k;
}

int main()
{
    
	int a = 10;
	int b = 20;
	int c = 30;

	swap(&a,&b);//  The incoming address is 

	printf("%d %d\n",a,b);

	return 0;
}

fourteen 、 Arrays as arguments to functions

Arrays as arguments to functions , Will degenerate directly into pointer type

void print_arr(int* b, int len)
{
    
	int n = sizeof(b) / sizeof(b[0]);// Print  1
	printf("%d\n",n);
	for (int i = 0; i < len; i++)
	{
    
		printf("%d ",b[i]);
	}
	printf("\n");
}

int main()
{
    
	int b[10] = {
    1,2,3,4,5,6,7,8,9,10};

	print_arr(b,10);

	return 0;
}

15、 ... and 、 Pointer as the return value of the function

The return is an address

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS
int num = 0;

int* getnum()
{
    
	//{} Variables defined in are called local variables , The space of local variables will be released after the end of the function 
	srand(time(NULL));
	num = rand();
	return &num;
}


int main()
{
    
	int* p = getnum();

	printf("%d", *p);

	return 0;
}

sixteen 、 Pointers and strings

16.1 Pointer and character array

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	char a[] = "helloworld";//  Defines an array of characters   The length is eleven , The contents of the character array are helloworld\0  It's a string 
	//  Define a pointer to hold the address of the first element of the array 
	char* p = a;
	printf("%s\n",p);// %s  Print a string   What you want is the address of the first character  
	//  The pointer p What you save is the address of the first character 
	return 0;
}

You can change a single character through a character array pointer

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	char a[] = "helloworld";//  Defines an array of characters   The length is eleven , The contents of the character array are helloworld\0  It's a string 
	//  Define a pointer to hold the address of the first element of the array 
	char* p = a;
	printf("%s\n",p);// %s  Print a string   What you want is the address of the first character  
	//  The pointer p What you save is the address of the first character 

	printf("%s\n",p + 2);

	*p = 'x';//  Change the character directly through the character pointer 
	p++;
	*p = 'o';
	printf("%s\n", a);

	return 0;
}

16.2 String constant

Assign a string constant to a pointer , The pointer saves the address of the string constant , You can print strings through pointers , But you can't modify the character of the string through the pointer

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	//  String exists in array   The stack area   Can be changed 
	char a[] = "helloworld";//  Defines an array of characters   The length is eleven , The contents of the character array are helloworld\0  It's a string 
	//  Define a pointer to hold the address of the first element of the array 
	char* p = a;
	p = "abcdef";//  String constants are stored in the text constant area , When use , Get the address of the first element of the string 
	//  The content of the text constant area cannot be changed 

	printf("%s\n",p);// %s  Print a string   What you want is the address of the first character  
	//  The pointer p What you save is the address of the first character 

	printf("%d\n",sizeof(p));// 4
	printf("%d\n",sizeof("abcdef"));// 7

	printf("%d\n",strlen(p));// 6
	printf("%d\n",strlen("abcdef"));// 6

	return 0;
}

16.3 Character pointer as function parameter

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS

char* my_strcat(char* src, char* dst)
{
    
	//  Concatenate two strings 
	int n = strlen(src);//  Calculate the number of valid characters 
	int i = 0;

	//  Loop through the second string 
	while (*(dst + i) != 0)
	{
    
		//  The cycle condition is   The current character is not \0

		// src  At the beginning, it points to the first character of the string   add n Then point to the character at the end of the string \0  And then directly cover \0
		*(src + n + i) = *(dst + i);
		i++;
	}
	*(src + n + i) = 0;//  add to \0 character 
	return src;
}

int main()
{
    
	char a[] = "zxcvb";
	char b[] = "wqeqwrrt";

	printf("%s\n",my_strcat(a,b));

	return 0;
}

16.4 Character pointer array

Character pointer array , Every element is a character pointer ( String address )

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    
	char* p1 = "heihei";
	char* p2 = "haha";
	char* p3 = "xixi";
	char *num[3] = {
    p1,p2,p3};//  Character pointer array   Every element is a character pointer ( String address )

	for (int i = 0; i < 3; i++)
	{
    
		printf("%s\n",num[i]);// num The address of the string is stored in 
	}

	printf("%c\n",*num[0]);//  Print  h
	printf("%c\n",*(num[1] + 1));//  Print a
	printf("%c\n",*(num[2] + 2));

	return 0;
}

 Insert picture description here

16.5 Character pointer array as main Function parameter

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS

//char* argv[] = { ".*.exe","hello","123456" };

int main(int argc,char *argv[])
{
    
	
	for (int i = 0; i < argc; i++)
	{
    
		// argc Represents the number of parameters 
		// argv Represents an array of pointers   The address of each parameter string is stored   Default argv[0] Is the address string of the program 
		for (int i = 0; i < argc; i++)
		{
    
			printf("%s\n",argv[i]);//  Pass in the string address   Print each string 
		}
	}

	return 0;
}

seventeen 、 String commonly used processing functions

  • String copy function stcpy
char str1[128] = ".";
char str2[128] = "world";
strcpy(str1,str2);
printf("%s\n",str1);

str2 It will cover directly from the beginning str1, And copy \0 character , So the following code will print world

char str1[128] = "hhhhhhhiiiiiii";
char str2[128] = "world";
strcpy(str1,str2);
printf("%s\n",str1);
  • strncpy String copy function
    take str2 Middle front n Copy characters to str1 in , If the copy is insufficient N individual , encounter \0 Copy end

  • strcat(str1,str2) String concatenation function
    take str2 String connected to dest Tail of ,\0 It will be added to the past , When you link , encounter \0 end

  • strncat(str1,str2,n)
    take str2 In character array N Copy characters to str1 Character array , encounter \0 end

  • strcmp(str1,str2) Compare strings
    str1 Array neutralization str2 The array takes out an element for comparison , Continue to think about the following comparison , The comparison is of characters ascii value , If str1 > str2 The return value is equal to 1,str1 == str2 The return value is equal to 0, If str1 < str2 The return value is equal to -1

  • sprintf(): Package function

int len = sprintf(buf,“ Format ”,“ data ”);// Package the data according to the format , Store in array buf in ,sprintf The return value of the function is the effective length of the finished package

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)

int main()
{
    
	int year = 2018;
	int month = 10;
	int day = 20;
	char buf[1024] = "";

	int len = sprintf(buf,"year = %d %c month = %d day = %d",year,0,month,day);
	printf("buf = [%s]\n",buf);//  encounter \0 Don't print 
	printf("%d\n",len);//  Return string length 
	
	return 0;
}

  • sscanf(): Unpack function

sscanf(buf,“ Format ”, data );// take buf Format the content in and output it to data

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)

int main()
{
    
	int year = 2018;
	int month = 10;
	int day = 20;
	char buf[1024] = "2018:10:20";

	sscanf(buf,"%d:%d:%d",&year,&month,&day);//  from Buf Get data in format 
	printf("%d %d %d\n",year,month,day);
	
	return 0;
}
  • strchr(str,‘c’) Intercept the string starting from a certain character
char str[] = "xixihellogworld";
char *p = strchr(str,'g);
printf("%s\n",p);//  Print gworld

Do it yourself

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)

char* my_strchr(char *p,char ch)
{
    
	int i = 0;
	while (*(p + i) != 0)
	{
    
		if (*(p + i) == ch)
		{
    
			// return (p + i);//  Address fetch 
			//  Or written 
			return &p[i];
		}
		i++;
	}

	if (*(p + i) == 0)
	{
    
		return NULL;
	}
}

int main()
{
    
	char str[] = "xixixihellogworld";
	char* p = my_strchr(str,'g');
	printf("%s\n",p);
	return 0;
}
  • strstr(str1,str2)

Intercept the remaining strings from a certain string

int main()
{
    
	char str[] = "xixiabcxihellogworld";
	char str1[] = "abc";
	char* p = strstr(str,str1);
	printf("%s\n",p);
	return 0;
}
  • strtok(str,“c”) Cut string
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)


int main()
{
    
	char str[] = "xixiab#cxihello#gworld";
	char* p1 = strtok(str,"#");//  stay str1 Lieutenant general # cutting , Return the string before cutting 
	printf("%s\n",p1);

	char* p2 = strtok(NULL,"#");
	printf("%s\n",p2);

	char* p3 = strtok(NULL,"#");
	printf("%s\n",p3);
	
	return 0;
}

  • atoi() function Convert string to integer

atoi() Will scan the string , Skip the preceding space character , Until you encounter a number or a plus or minus sign and start converting , Encountered non numeric or string terminator \0 End the transition , And return the result to the return value integer .

char num[] = "123";
int sum = atoi(num);

Allied atof() Convert to decimal

eighteen 、 String case

18.1 Find the number of times a string appears in the string

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)

int strstr_num(char* src, char* dst)
{
    
	int i = 0;
	char* p = src;
	int n = 0;

	do
	{
    
		p = strstr(p,dst);

		if (p != NULL)
		{
    
			//  If the address returned from the search is not NULL  It means that 
			n++;
			p = p + strlen(dst);
		}

	} while (p != NULL);

	return n;
}

int main()
{
    
	char src[] = "hdabchabchjfsjabcjdsjabc";
	char dst[] = "abc";
	int n = strstr_num(src,dst);
	printf("%d\n",n);
	return 0;
}

18.2 Two plug model


int main()
{
    
	char buf[] = " hello world ";
	char dst[128] = "";
	
	char* start = buf;
	char* end = &buf[strlen(buf) - 1];// end Point to the last character 

	//  Find the first position that is not a space 
	while (*start != ' ' && *start != 0)
	{
    
		start++;
	}

	while (*end != ' ' && end != start)
	{
    
		end--;
	}

	printf("%d\n",end - start + 1);//  Print length 
	strncpy(dst,start,end - start + 1);
	printf("%s\n",dst);

	return 0;
}

18.3 String flip

int main()
{
    
	char buf[] = "abcdef";
	char* start = buf;
	char* end = &buf[strlen(buf) - 1];//  Go to the last character 

	while (end > start)
	{
    
		char ch = *end;
		*end = *start;
		*start = ch;
		end--;
		start++;
	}
	printf("%s",buf);
	return 0;
}

原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230134315223.html