C language learning - day04

Posted by sheilam on Thu, 03 Mar 2022 05:50:03 +0100

Learning source: station b -- Author: Little Turtle-- [C language] C language video tutorial(Lonely self-study - up master)

Multidimensional arrays and pointers

Pointer variables can point to either elements in a one-dimensional array or elements in a multi-dimensional array.

For example: int a [3] [4] = {1,3,5,7}, {9,11,13,15}, {17,19,21,23}; The address of a [0] [0] is 2000.

Representationmeaningaddress
aTwo dimensional array name, pointing to one-dimensional array a[0], that is, the address at the beginning of line 02000

a[0]

*(a+0)

*a

0 row 0 column element address2000
a+1, &a[1]1 line beginning address2016

a[1]+2

*(a+1)+2

&a[1][2]

Address of 1 row 0 column element a[1][0]2024

*(a[1]+2)

*(*(a+1)+2)

a[1][2]

Value of element a[1][2] in row 1 and column 2The element value is 13

Title: output values related to two-dimensional array

#include <stdio.h>

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

    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));

    printf("a[1]: %d\n", a[1]);

    printf("&a[1]: %d\n", &a[1]);

    printf("&a[1][0]: %d\n", &a[1][0]);

    printf("a+2: %d\n", a+2);

    printf("*(a+2): %d\n", *(a+2));

    printf("a[2]: %d\n", a[2]);

    printf("&a[2]: %d\n", &a[2]);

    printf("&a[2][0]: %d\n", &a[2][0]);

    printf("a[1]+1: %d\n", a[1]+1);

    printf("*(a+1)+1: %d\n", *(a+1)+1);

    printf("*(a[1]+1): %d\n", *(a[1]+1));

    printf("*(*(a+1)+1): %d\n", *(*(a+1)+1));

}

result:

Title: print out all elements 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];

    int i, j, row, colum;
    
    scanf("%d %d",&row,&colum);

    p = a;

    for( i=0; i < 3; i++)
    {
          for( j=0; j < 4; j++) 
          {
              if(i == row || j == colum)
              {
                  printf("%6d", *(*(p+i)+j));
              }
              else
              {
                  printf("%6c",' ');
              }
                
                
          }
          printf("\n");
    }
}

Input: 1 2

result:

Title: copy string a to string b

Solution 1 (subscript method)

#include <stdio.h>

void main()
{
      char a[] = "I love dog!", b[40];
      int i;
      
      for(i=0; *(a+i) != '\0'; i++)
      {
            b[i] = a[i];
      }
      *(b+i) = '\0';

      printf("String a is: %s\n", a);
      printf("String b is: ");
      for(i=0; b[i] != '\0'; i++)
      {
            printf("%c", b[i]);
      }
      
      printf("\n\n");
}

result:

Solution 2 (pointer method)

#include <stdio.h>

void main()
{
      char a[] = "I love dog!", b[40], *p1, *p2;
      int i;
      
      p1 = a;
      p2 = b;
      
      for( ; *p1 != '\0'; p1++, p2++)
      {
            *p2 = *p1;
      }
      *p2 = '\0';

      printf("String a is: %s\n", a);
      printf("String b is: ");
      for(i=0; b[i] != '\0'; i++)
      {
            printf("%c", b[i]);
      }

      printf("\n");
}

result:

The difference between character array and character pointer variable

        1. The character array consists of several elements, one character in each element, and the address (the address of the first character of the string) is stored in the character pointer variable.

        2. You can only assign values to each element of a character array, not str = "I love dog.", For character pointer variables, you can use a = "I love dog." But it is not the character assigned to a, but the address of the first element of the string.

        3. Different initialization methods:

//Initialization of character pointer
char *a = "I love dog.";

//Equivalent to
char *a;
a = "I love dog.";

//Array initialization
char str[20] = {"I love dog."};

//Cannot be equivalent to
char str[20];
str[] = "I love dog."; 

        4. If a character array is defined, memory units are allocated to it at compile time, and it has a definite address. When defining a character pointer variable, a memory unit is allocated to the pointer variable, in which the address of a character variable can be placed, that is, the pointer variable can point to a character data, but if it is not given an address value, it does not specifically point to a certain character data.  

        5. The value of pointer variable can be changed. Note: if a pointer variable points to a string, the character in the string pointed to by the pointer variable can be referenced by subscript.

#include <stdio.h>

void main()
{
      char *a = "I love dog.";
      printf("%s\n", a);

      a += 7;
      printf("%s\n", a);
}

result:

#include <stdio.h>
void main()
{
      char *a = "I love dog.";
      int i;

      printf("The sixth is %c\n", a[5]);

      for( i=0; a[i] != '\0'; i++ )
      {
            printf("%c", a[i]);
      }

      printf("\n");
}

result:

Pointer to function

Title: use the pointer to the function to realize the use of the maximum function

#include <stdio.h>
int max(int x, int y)
{
      int z;
      
      if( x > y )
      {
            z = x;
      }
      else
      {
            z = y;
      }

      return z;
}


void main()
{
      int max(int, int);
      int (*p)();
      int a, b, c;

      p = max;
      scanf("%d %d", &a, &b);
      
      c = (*p)(a, b);
      
      printf("a = %d, b = %d, max = %d\n\n", a, b, c);
}

result:

Pointers to functions can also be used as arguments to functions

void f3(int (*x1)(int),int(*x2)(int,int))
{
    int a, b, i, j;
    a = (*x1)(i);
    n = (*x2)(i,j);
}

In this function, x1 and x2 are pointer variables pointing to the function respectively. When calling f3 function, the actual parameters are two function names f1 and f2, and the addresses of f1 and f2 are passed to the formal parameters, so that f1 and f2 can be called in f3 function.

Function that returns pointer value

General definition form: type name * function name (parameter list)

Title: there are scores of several students (each student has 4 courses). It is required to output all the scores of the student after the user enters the student serial number. It is realized by pointer function.

#include <stdio.h>
void main()
{
    int score[3][4] = {{70,80,90,50},{90,90,90,90},{60,60,60,60}};
    int *search(int (*pointer)[4],int n);
    int *p;
    int i,m;
    scanf("%d",&m);
    
    p = search(score,m);
    
    for (i = 0; i < 4; i++) {
        printf("%5d",*(p+i));
    }
}

int *search(int (*pointer)[4],int n)
{
    int *pt;
    pt = *(pointer+n);
    return pt;
}

Input: 2

result:

The difference between pointer function and function pointer

The pointer is a function type, and the return value of a function is the essence of the pointer; A function pointer is a pointer variable that points to a function, so the function pointer itself is a pointer variable.

Pointer array and pointer to pointer

Each element of the pointer array is pointer type data. The general form of one-dimensional pointer array is: type name, array name [length];

#include <stdio.h>

void main()
{
      int a[5] = {1, 3, 5, 7, 9};
      int *name[5] = {&a[0], &a[1], &a[2], &a[3], &a[4]};
      int i;

      for( i=0; i < 5; i++ )
      {
            printf("%d   ", *name[i]);
      }
      printf("\n\n");
}

result:

General form of pointer pointing to pointer: type name * * pointer name

#include <stdio.h>
int main()
{
      char *name[] = {"I love", "dog", "cat"};
      char **p;
      int i;

      for( i=0; i < 3; i++ )
      {
            p = name + i;
            printf("%s\n", *p);
      }
}

result:

void pointer

The pointer does not point to a certain type of data, but is only used to store an address.

Void pointers can point to any type of data. In other words, any type of pointer can be used to directly assign a value to the coid pointer. However, if the value of the void pointer needs to be assigned to other types of pointers, forced type conversion is required.

const pointer

const char *str= "I love dog!\n\n";
//str[0] = 'w', this method is wrong
str = "I love cat!\n\n";   //This way is legal


char * const str = "I love dog!\n\n";
str[0] = 'w'  //legitimate
//str = "I love cat!\n\n";   illegal



const char * const str = "I love dog!\n\n";
str[0] = 'w'  //illegal
//str = "I love cat!\n\n";   illegal

Summary

Summary of data types of pointers

definitionmeaning
int i;Pointer variables that define integer data
int *p;p is a pointer variable pointing to integer data
int a[n];Defines an integer array a, which has n elements
int *p[n]

Defines the pointer array p, which is composed of n pointer elements pointing to integer data

int (*p)[n]

p is a pointer variable pointing to a one-dimensional array containing n elements

int f()f is a function that brings back an integer value
int *p()p is a function that brings back a pointer to integer data
int (*p)()

p is a pointer to a function that returns an integer value

int **pp is a pointer variable that points to a pointer variable that points to integer data

Pointer variable assignment

p = &a; Assign the address of variable a to P

p = array; Assign the address of the first element of array to P

p = &array[i]; Assign the address of the ith element of the array to P

p = max; Max is a defined function. Assign the entry address of Max to P

p1 = p2; Both p1 and P2 are pointer variables. Assign the value of P2 to P1

The pointer variable can have null value, that is, the pointer variable does not point to any variable, which can be expressed as follows: p = NULL;

Two pointer variables can be subtracted. If both pointer variables point to elements in the same array, the difference between the values of the two pointer variables is the number of elements between the two pointers.

If two pointers point to elements of the same array, they can be compared. The pointer variable pointing to the preceding element is less than the pointer variable pointing to the following element.

Today's summary: After reviewing the pointer today, there is a structure behind it. Continue to refuel!

Topics: C