C language: essay 6-pointer 1.2

1. Multidimensional arrays and pointers

Pointer variables can be used to point to elements in one-dimensional arrays or to elements in multi-dimensional arrays. The array name of an array is the first address of the array, and the pointer variable stored in it happens to be an address. We only need to store the first address of a one-dimensional array in this pointer variable, then we say that this pointer points to this array.

The following is an array with 3 rows and 4 columns. The storage in the memory is actually stored in a linear arrangement.

  

#include<stdio.h>
void main()
{
   int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11,12};
   printf("a:%d\n",a);
   printf("*a:%d\n",*a);
   printf("a[0]:%d\n",a[0]);
   printf("&a[0]:%d\n",&a[0]);
   printf("&a[0][0]:%d\n",&a[0][0]);
   printf("a+1:%d\n",a+1);
   printf("*(a+1):%d\n",*(a+1));
}

Decompose the two-dimensional array a into a one-dimensional array a[0] (our a[0] points to four elements again, a[0] stores an address, this address has four elements, then that is It is a two-dimensional array,), after a[1] (similarly), a[2] (similarly) (indicating that this is a two-dimensional array of a3x4, the concept is when my one-dimensional array is inside the element When the address of another array is stored, it is a two-dimensional array, because my element a[0] is not finished yet, and it also points to an address. This address is the address of an array, which is a two-dimensional array. ), let p be a pointer variable pointing to a two-dimensional array. Can be defined as:

int (*p)[4];//它表示p是一个指针变量,它指向包含四个元素的一维数组。若指向第一个一维数组a[0],其值等于a,a[0],或者&a[0][0]等。
//而p+i则指向一维数组a[i];因为p指向的是a的地址。
//从前面的分析可以得出*(p+i)+j是二维数组i行j列的元素的地址,而*(*(p+i)+j)则是i行j列元素的值
//怎么理解呢?????????
//因为我们之前解释,如果一维数组里面存放的是另外一个数组的地址那它就是一个二维数组。
//那我们这里p+i也就是说一维数组第几个元素取出他的值(比如是a[i],*(p+i)是一个地址值,**(p+i)才是对应第i行的首个元素值)
也就是相应一个二维数组的一个元素的初始地址,再加上j就是这个二维数组的偏移地址,第几列,然后我们再把总共的取出他的值。

//The general form of the two-dimensional array pointer variable description is:

Type specifier (*pointer variable name) [length]

The "type specifier" is the data type of the index group. "*" means that the following variable is a pointer type. "Length" indicates the length of the one-dimensional array when the two-dimensional array is decomposed into multiple one-dimensional arrays, that is, the number of columns of the two-dimensional array. (// Shouldn't the previous one be declared as the number of rows? Shouldn't the number of rows need to be defined?). The number of rows does not need to be defined, what is the number of rows. That is to say, the specific length of a one-dimensional array depends on the value we assign to it, and how many values ​​it assigns it automatically. So we directly give a pointer to the first address of its row number.

Example: Use a pointer to output the value of a two-dimensional array element variable

#include<stdio.h>
void main()
{
    int a[3][4]={};
    int (*p)[4];//定义一个二维数组的指针,指向二维数组//切记(*p)中的括号一定要带
    p=a;//将二维数组的地址指向了这个指针的地址
    int i,j;//定为i和j来定义行和列
    for(i=0;i<3;i++)
    {
       for(j=0;j<4;j++)
       {
          printf("%2d",*(*(p+i)+j));
       }
       printf("\n");
    }
}

Example: Print out the value of any row or column element of a two-dimensional array by entering the specified number of rows and columns.

#include<stdio.h>
void main()
{
   int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11};
   int (*p)[4],i,j;
   p=a;
   printf("i=");
   scanf("%d",&i);
   while(i>2||i<0)
   {
      printf("i=");
      scanf("%d",&i);
   }
   printf("j=");
   scanf("%d",&j);
   while(j>3||i<0)
  {
      printf("j=");
      scanf("%d",&j);
  }
  printf("a[%d,%d]=%d\n",i,j,*(*(p+i)+j));//经过两次取值
}

2. Strings and pointers

(1) Use a character array to store a character string, and then output the character string.

Example: Define a character array, initialize it, and then output the string. (Define the string in the form of a character array)

#include<stdio.h>
void main()
{
   char string[]="I Love Fishc.com!";//不定义长度,让编译器自行计算
   printf("%s\n",string);//s就是字符串的形式打印,给他一个地址,给他字符串的首地址他就会依次打印直到出现'\0'字符他就停止打印。
}

The following shows that the elements are stored in sequence, and the space also occupies one element. Add a'\0' at the end. The character \0 is equivalent to the integer 0 in ASCII.

(2) Point to a character string with a character pointer.

Example: You can define a character pointer instead of defining a character array. Use the character pointer to point to the character in the string.

#include<stdio.h>
void main()
{
    char *string="I Love Fishc.com!";//这里定义的是一个字符指针,不再是一个字符串
    printf("%s\n",string);
}

(3) To access the characters in the string, you can use the subscript method or the pointer method.

Example: Copy string a to string b

//下标法举例
#include<stdio.h>
void main()
{
    char a[]="A is a good man!",b[40];
    int i;
    for(i=0;*(a+i)!='\0';i++)//只要a数组的这个元素不为0,0就是字符串结束的标志
    {
        *(b+i)=*(a+i);//不为0的话就依次copy过去
    }
    *(b+i)='\0';//然后最后还应该把他补上0因为我们这个是字符串,如果没有补上的话,他就不知道字符串的结尾是哪里,她就会把内存中相关的我们定义的40个字符嘛,这些随机的数据他都会把它当成字符串给他显示出来直到没有。
    printf("String a is:%s\n",a);
    printf("String b is:");//2也可以直接打印b
    for(i=0;b[i]!='\0';i++)
    {
       printf("%c",b[i]);//1使用了数组的索引方式打印的
    }
    printf("\n\n");
}

The method of using pointers is that the transmission in the iterative loop is different

//下标法举例
#include<stdio.h>
void main()
{
    char a[]="A is a good man!",*p1,*p2;//定义的两个指针分别指向数组a和数组b,那么我取出p1的值也就相当于取出a的值
    int i;
    p1=a;
    p2=b;
    for(;*p1!='\0';p1++,p2++)//++就是递增1,往后边元素,指向后边元素
    {
        *p2=*p1;//不为0的话就依次copy过去
    }
    *p2='\0';//然后最后还应该把他补上0因为我们这个是字符串,如果没有补上的话,他就不知道字符串的结尾是哪里,她就会把内存中相关的我们定义的40个字符嘛,这些随机的数据他都会把它当成字符串给他显示出来直到没有。
    printf("String a is:%s\n",a);
    printf("String b is:");//2也可以直接打印b
    for(i=0;b[i]!='\0';i++)
    {
       printf("%c",b[i]);//1使用了数组的索引方式打印的
    }
    printf("\n\n");
}

(4) Character pointer as function parameter

Use function call to implement string assignment

(1) Use character arrays as parameters.

(2) Use character pointer variables for formal parameters.

//设一个函数process,在调用他的时候,每次实现不同的功能。
//输入a,b第一次调用process时找最大,第二次找最小,第三次求和。
#include<stdio.h>
void main()
{
   int max(int,int);
   int min(int,int);
   int add(int,int);
   void process(int,int,int(*fun)());
   int a,b;
   printf("Enter a and b:");
   scanf("%d %d",&a,&b);
   printf("max=");
   process(a,b,max);
   printf("min=");
   process(a,b,min);
   printf("add");
   process(a,b,add);
}
int max(int x,int y)
{
   int z;
   if(x>y)
   {
      z=x;
   }
   else
   {
      z=y;
    }
   return z;
}

(5)

(6) Functions that return pointer values

A function can bring back an integer value, character value, real value, etc., or pointer data, that is, an address. The concept is similar to before, except that the type of the returned value is a pointer type.

This kind of function that brings back the pointer value is generally defined as:

类型名 *函数名(参数列表);
//例如:
int *a(int x,int y);//加上*号表示带回来的是指向整型的指针。如果不带回什么就void

Example: There are several students' grades (each student has 4 courses). After the user enters the student's serial number, all grades of the student can be output, which can be realized by pointer function.

#include<stdio.h>
void main()
{//用二维数组每一行表示每一个同学,4个列表示4门课程
   double score[][4]={
   
   {},{},{},{}};
   double *search(double(*pointer)[4],int n);//定义了一个指针函数(他首先是一个函数,因为有一个括号,接着返回指针类型,这个指针还是指向double的指针)
   double *p;
   int i,m;
   printf("PLease enter the number of student:");
   scanf("%d",&m);
   
   printf("The scores of No.%d are:",m);
   p=search(score,m);//3返回值给p把他的地址给p,然后下边再打印出来。
   for(i=0;i<4;i++)//打印第m行的元素值;p代表第m 行的首地址
   {
       printf("%5.2f\t",*(p+i));
   }
   printf("\n\n\n")
}
double *search(double(*pointer)[4],int n)
{
   double *pt;
   pt=*(pointer+n);//1序号加上行数的索引,取出来的就是说某一个学生的一个归于那一行地址的一个索引,然后再返回
   return pt;//2返回的是二维数组第n行的首地址
}

For the students in the above example, find the students who failed the course and their student numbers. (Compare, extract each result, if it is less than 60, Ok will return the pointer of this array, and then receive the pointer and print out his corresponding person)

//代码

PS: The difference between pointer function and function pointer (both concepts are abbreviations)

Pointer function: refers to a function with a pointer, which is essentially a function.

Function pointer: It is a pointer variable that points to a function, so the function pointer itself is a pointer variable first, but the pointer variable points to a function.

(7) Pointer array and pointer to pointer

The concept of an array of pointers (an array after all):

If the elements of an array are pointer-type data, it is called a pointer array. In other words, each element in the pointer array is equivalent to a pointer variable (that is, a bunch of pointer variables stand in line). The definition of a one-dimensional pointer array is:

类型名 数组名[数组长度];
//例如:
int *name[4];//*表示他是一个指针

(8) Summary

5. Comparison of two pointer variables

If two pointers point to an element of the same array, they can be compared, and the pointer variable pointing to the previous element is "less than" the pointer variable pointing to the next element. (In fact, the comparison is that the two pointers point to the serial number of the array element)

6, void type

Void really plays a role: (1) the restriction on the return type of the function; (2) the restriction on the function parameter type.

The void type is used for pointers. The new ANSIC standard adds a "void" pointer type, that is, it does not specify which type of data pointer variable it points to. (He is an empty type, nothing, just put an address, what variable does an address point to? I don’t know yet. But we can turn it into an integer through a bracket int ()int, or ( )Other types)

For example, void *p; indicates that the pointer variable p does not point to a certain type of data, and its function is only to store an address.

The void pointer can point to any type of data (because it is empty), that is to say, you can use any type of pointer to directly assign the void pointer, but if you need to assign the value of the void pointer to other types of pointers, you need to do Force type conversion.

7. Use three examples to talk about const (pointer)

#include<stdio.h>
void main()
{
    const char *str="Welcome to!\n\n";
   //这个语句的含义是:声明一个名为str的指针变量,他指向一个字符型常量,初始化str为指向字符串"Welcome to\n\n"
//再声明他为const就是常量(就是是一个变量常量化使他不能够被改变)
#if(0)//宏定义//如果改为1让他编译就会报错:L-value specifies const object.(因为常量对象是不能被赋值的,不能充当左值的)
    str[0]='w';//这条语句是错误的,但可以改变str指针的值。
#enfif
    str="I Love!\n\n";//合法//我们强制把他的地址改变成指向"I Love!\n\n"
    printf("\n\n%s",str);
}

Modify the above

#include<stdio.h>
void main()
{
    char *const str="Welcome to!\n\n";//存放在常量的data区
   //常量指针是一个固定的指针,不可以改变它的值,但它所指的数据可以改变。
   str[0]='w';//windows禁止常量被重写(所以我这里把他重写为小写的w他就不给写)//但是编译是符合c语言的语法规范的
#if(0)
    str="I Love!\n\n";//非法
//从上边可以看到const接近str这个指针的时候,说明把这个指针定义为const变量了,他就不能被修改。
//如果说把const放在前面,那就是定义每一个字符是一个const常量不能被替换。
#enfif
    printf("\n\n%s",str);
}

Modify it again:

#include<stdio.h>
void main()
{
    const char *const str="Welcome to!\n\n";//存放在常量的data区
   //两边都是const变量
   str[0]='w';//非法
   str="I Love!\n\n";//非法

    printf("\n\n%s",str);
}

API function: memcpy

//copyes characters between buffers
void *memcpy(void *dest,const void*src,size_t count)

 

Guess you like

Origin blog.csdn.net/m0_37957160/article/details/108578515