Introduction to C language

Posted by monezz on Sun, 21 Nov 2021 04:45:29 +0100

1. Application scenario of pointer

(1),

Exchange the values of two variables

#include <stdio.h>
void swap(int *pa,int *pb);
int main()
{
	int a=5;
	int b=6;
	swap(&a,&b);
	printf("a=%d,b=%d\n",a,b);
	return 0; 
}

void swap(int *pa,int *pb){
	int t = *pa;
	*pa = *pb;
	*pb = t;
}

(2),

Function returns multiple values, and some values can only be returned through pointers;

The returned parameters are actually variables that need to save the brought back results;

#include <stdio.h>
void minmax(int a[],int len,int *min,int *max);
int main(void)
{
	int a[]={1,2,3,4,5,6,7,8,9,12,13,14,16,17,21,23,55,};
	int min,max;
	minmax(a,sizeof(a)/sizeof(a[0]),&min,&max);
	printf("min=%d,max=%d\n",min,max);
	return 0; 
}

void minmax(int a[],int len,int *min,int *max){
	int i;
	*min = *max =a[0];
	for(i=1;i<len;i++){
		if(a[i]<*min){
			*min=a[i];
		}
		if(a[i]>*max){
			*max=a[i];
		}
	}
}

(3),

Function returns the state of the operation, and the result is returned through the pointer;

A common routine is to let the function return a special value that does not belong to the valid range to indicate an error:, - 1 or 0 (you will see a lot of examples in file operations);

When both people and values are valid possible results, they have to be returned separately;

#include <stdio.h>
int devide(int a,int b,int *result);
int main(void)
{
	int a=5;
	int b=2;
	int c;
	if(devide(a,b,&c)==1)//If (devide (a, B, & C)) is True by default, that is, the value is 1 
	{
		printf("%d/%d=%d\n",a,b,c);
	}
	return 0; 
}

int devide(int a,int b,int *result){
	int ret = 1;
	if(b==0) ret = 0;//If it is in the main function, an error will be reported and cannot be performed 
	else *result=a/b;
	return ret;
}

2. Common errors in pointers:

The pointer variable is defined, including no pointer to any variable, which means that you can't assign a value to it casually, so you start to use the pointer;

#include <stdio.h>
void f(int *p);
void g(int k);
int main(void)
{
	int i=6;
	int *p;
	
	printf("&i=%p\n",&i);
	
	f(&i);
	g(i);
	
	return 0; 
}

void f(int *p){
	printf(" p=%p\n",p);
	printf("*p=%p\n",*p);
	*p=26;
}

void g(int k){
	printf("k=%d\n",k);
}

3. What does the number of incoming functions make up?

(Explore Based on minmax function)

#include <stdio.h>
void minmax(int a[],int len,int *min,int *max);
int main(void)
{
	int a[]={1,2,3,4,5,6,7,8,9,12,13,14,16,17,21,23,55,};
	int min,max;
	printf("main sizeof(a)=%lu\n",sizeof(a));//The size of the array in the main function 
	printf("main a=%p\n",a);//Address of array a in main 
	minmax(a,sizeof(a)/sizeof(a[0]),&min,&max);
	printf("min=%d,max=%d\n",min,max);
	return 0; 
}

void minmax(int a[],int len,int *min,int *max){
	int i;
	printf("minmax sizeof(a)=%lu\n",sizeof(a));//The size of the array in the minmax function
	printf("minmax a=%p\n",a);//Address of array a in minmax
	*min = *max =a[0];
	for(i=1;i<len;i++){
		if(a[i]<*min){
			*min=a[i];
		}
		if(a[i]>*max){
			*max=a[i];
		}
	}
}

come to conclusion:

All array addresses are the same. Modifying the value of the element of the array in the minmax function will also change the value of the element of the corresponding array in the main function;

The array definition in the parentheses of the function is actually the address. int *a is equivalent to int a [];

Array variables themselves express addresses, but array cells express variables;

4. What does const do?

(1) const array

const int a[] = {1,2,3,4,5,6,};

The array variable is already a pointer to const. Const here indicates that each cell of the array is const int, so it must be assigned through initialization.

(2) , conversion

It is always possible to convert a non const value to const

void f(const int *x);

int a=15;

f(&a);//ok

const int b = a;

f(&b);//ok

b = a + 1;//Error

This is a common method when the parameter type to be passed is larger than the address;

It can not only be passed to parameters with a relatively small number of bytes, but also avoid the modification of external variables by the function.

(3) , protect the value of the array

Because the address is passed when the array is passed into the function, the value of the array can be modified inside the function;

To protect the array from being destroyed by the function, you can set the parameter const:

int sum(const int a[],int length);

5. Pointer operation

(1) , address + 1, is it really the value of address + 1?

#include<stdio.h>
int main(){
	char ac[] = {0,1,2,3,4,5,6,7,8,9,};
	char *p = ac;
	printf("p  =%p\n",p);
	printf("p+1=%p\n",p+1);
	return 0;
}

Here, change the variable type, and a strange phenomenon occurs:

  This is because: sizeof (char) = 1; sizeof(int)=4;

(2),

*When p+1, add 1 to the value of the first element of the array pointed to by the pointer;

*(p+1) is the second element of the array pointed to by the pointer;

Arithmetic operators can do the following to pointers:

Add or subtract an integer (+, + =, - =) to the pointer;

Increasing decreasing (+ + / -);

Subtract two pointers;

  The difference between the two addresses is not the difference between the values of the addresses, but their difference / sizeof (variable type);

(3) , * p + + is equivalent to * (p + +)

Take out the data referred to by P, and move p to the next position when it is finished;

*Although the priority of is high, it is not as high as + +;

It is often used for continuous space operations of array classes;

On some CPU s, this can be translated directly into an assembly instruction;

Another way to traverse an array:

#include<stdio.h>
int main(){
	//for loop traversal 
	char ac[] = {0,1,2,3,4,5,6,7,8,9,};
	char *p = ac;//Equivalent to char * P = & AC [0];
	int i;
	for(i=0;i<sizeof(ac)/sizeof(ac[0]);i++){
		printf("%d\n",ac[i]);
	}
	printf("***********");
	//while traversal 
	char ai[] = {0,1,2,3,4,5,6,7,8,9,-1,};
	char *q = ai;
	while(*q != -1){
		printf("%d\n",*q++);
	}

	return 0;
}

(4) Comparison of and pointers

<,<=,==,>,>=,!= Can be done on the pointer;

Compare their addresses in memory;

The addresses of the cells in the array must be linearly increasing;

6. 0 address

<1> Your memory consists of 0 address, but 0 address is usually an address that can't be touched casually;

<2> So your pointer should not have a value of 0;

<3> Therefore, the 0 address can be used to represent special things:

The returned pointer is invalid, and the pointer is not really initialized (initialized to 0 first);

<4> Null is a predefined symbol that represents the 0 address. Some compilers don't want you to use 0 to represent the 0 address;

7. Type of pointer

No matter what type it points to, the size of all pointers is the same, because they are addresses;

However, pointers pointing to different types cannot be directly assigned to each other;

This is to avoid using wrong pointers;

8. Pointer type conversion

void * indicates that the pointer pointing to something is unknown: it is the same as char * in calculation (but not interlinked);

Pointers can also be converted to type: int * P = & I;   void *p = (void*)p;

This does not change the type of variable referred to by p, but allows future generations to look at the variable referred to by p with different eyes, which means: I am not here. When you are int, I think you are a void!

9. Dynamic memory allocation

(1) Input data: first tell you the number, and then input. Record each data;

C99 can use variables to define the size of the array,

Before that, use dynamic memory allocation:

int *a = (int*)malloc(n*sizeof(int));

(2) malloc is a function, which means how much memory I want (the above is equivalent to the number * the size of a single, in bytes). You can use it as an array below, and remember to return it at last;

(int *) is type conversion. This function is originally of void type;

#include<stdio.h>
#include<stdlib.h>
int main(){
	int number;
	int* a;
	int i; 
	
	printf("Enter quantity:");
	scanf("%d",&number);
	//int a[number];//C99 
	
	a = (int*)malloc(number*sizeof(int));//How much memory do you want? You can use it as an array below 
	//Get input data 
	for(i=0;i<number;i++){
		scanf("%d",&a[i]);
	}
	//output data
	for(i=number-1;i>=0;i--){
		printf("%d",a[i]);//Even an array 
	} 
	free(a);//Remember memory 
	return 0;
}

(3) How much space can your system give you?

#include<stdio.h>
#include<stdlib.h>
int main(){
	void *p;
	int cnt = 0;
	while( (p=malloc(100*1024*1024)) ) //The value in parentheses is the memory size 
	{
		cnt++;
	}
	printf("Assigned%d00MB Space of\n",cnt);
	return 0;
}

No space: if the application fails, it returns 0, or NULL.

free(): return the requested space to the "system". Only the first address of the requested space can be returned (it cannot be changed),

               free (NULL) can also be implemented, with borrowing and returning;

Topics: OpenCV AI Computer Vision