C language programming study notes (five)

Chapter XI pointers and arrays

/ * Array is given Once defined, the compiler system will assign a fixed storage unit in the memory, the corresponding first address in the array also determined

C language array name has a special meaning, it represents the first continuous memory address space storage array elements * /

 

// L11-1

#include <stdio.h>

int main ()

{

         int  a[5], i;

         printf("Input five numbers:");

         for (i=0; i<5; i++)

         {

                  scanf ( "% d", & a [i]); / * array element referenced by the standard method * /

         }

         for (i=0; i<5; i++)

         {

                  printf ( "% 4d", a [i]); / * array element referenced by the standard method * /

         }

         printf("\n");

         return 0;

}

 

//operation result

Input five numbers:1 2 3 4 5

   1   2   3   4   5

  

/ * Array represents the expression a + i is the subscript of the element i a [i] is the address (& a [i])

Thus the array may be referenced by elements of indirect addressing

* (A + i) represents the contents of the first address after the removal of the i-th element, i.e., a [i] * /

 

/ * Pointer arithmetic and relational operators often for the purposes of the array elements

If a pointer to the integer data pointer variable p, and with a value of a first address array

Then the elements of the array can be accessed by the pointer in a variable p

 

p + 1 and p ++ different operating

p + 1 of the pointer does not change the current

p ++ is equivalent to moving a pointer variable element forward position

 

is p ++ plus 1 * sizeof (base type) byte pointer variable * /

 

/ * The array name with the point and with a one-dimensional array as a function of the argument pointer variable, the start address of the called function is passed the array, are simulated call by reference

For one-dimensional array, with the array as a function parameter as a function of the variable and pointer shaped essentially the same parameters, the start address because they are receiving array

         This address are required for indirect addressing of the calling function in the real parameters * /

 

// L11-2

#include <stdio.h>

void InputArray(int a[], int n);

void OutputArray(int a[], int n);

int main ()

{

         int  a[5];

         int *p = a;

         printf("Input five numbers:");

         InputArray (p, 5); / * a one-dimensional array of points as a function of the argument pointer variable * /

         OutputArray (p, 5); / * a one-dimensional array of points as a function of the argument pointer variable * /

         return 0;

}

 

void InputArray (int a [], int n) / * parameter declared as an array, the array element value input * /

{

         int  i;

         for (i=0; i<n; i++)

         {

                  scanf ( "% d", & a [i]); / * access array elements with subscript method * /

         }       

}

void OutputArray (int a [], int n) / * parameter declared as an array, output array element values ​​* /

{

         int  i;

         for (i=0; i<n; i++)

         {

                  printf ( "% 4d", a [i]); / * access array elements with subscript method * /

         }

         printf("\n");        

}

 

// pointer relationship with the two-dimensional array

/* int a[3][4];

a [i] can be regarded as a [i] [0], a [i] [1], a [i] [2], a [i] [3] of the four elements of a one-dimensional array of integers the array name

         The representative of a first one-dimensional array of elements a [i] [0] address (& a [i] [0])

a [i] + j i.e. * (a + i) + j representative of the array element address index j, (& a [i] [j])

* (A [i] + j) immediately * (* (a + i) + j) representative a [i] [j] * /

 

// two-dimensional array of row pointer and a column pointer

/* int a[3][4];

Row pointer

int (* p) [4];

It can define a pointer to a variable-dimensional integer array containing four elements

Also be used as a pointer to a two-dimensional array of pointer variables, each row of the two-dimensional array to which it points is four elements

initialization

p = a;

p = &a[0];

Quote

p[i][j];

*(p[i]+j);

*(*(p+i)+j);

(*(p+i))[j];

Column pointer

int * p;

initialization

p = a[0];

p = *a;

p = &a[0][0];

Quote

p+i*n+j代表&a[i][j]

p [i * n + j] some * (p + i * n + j) representative a [i] [j] * /

 

// L11-3

#include <stdio.h>

void InputArray(int *p, int m, int n); 

void OutputArray(int *p, int m, int n); 

int main ()

{

         int  a[3][4];

         printf("Input 3*4 numbers:\n");

         InputArray (* a, 3, 4); / * 0 is transmitted first address line 0 of the two-dimensional array of function * /                     

         OutputArray (* a, 3, 4); / * 0 is transmitted first address line 0 of the two-dimensional array of function * /  

         return 0;

}

/ * Parameter declared to point to the two-dimensional array column pointer, array element value input * /

void InputArray(int *p, int m, int n)  

{       

         int i, j;

         for(i = 0; i<m; i++)

         {

                  for(j = 0; j<n; j++)

                  {

                          scanf("%d", &p[i*n+j]);        

                  }

         }

}

/ * Parameter declared to point to the two-dimensional array column pointer, the output value of the array element * /

void OutputArray(int *p, int m, int n)

{

         int i, j;

         for(i = 0; i<m; i++)

         {

                  for(j = 0; j<n; j++)

                  {

                          printf("%4d", p[i*n+j]);        

                  }

                  printf("\n");

         }

}

 

//operation result

Input 3*4 numbers:

1 2 3 4 5 6 7 8 9 10 11 12

   1   2   3   4

   5   6   7   8

   9  10  11  12

 

// array of pointers

/ * Array composed of a plurality of the same base type pointer, an array of pointers called

Each element in the array pointer is a pointer, and pointers to the same type of data variables

Due to the elements of the array pointer is a pointer, the pointer must be initialized prior to use array elements in the array of pointers * /

 

// L11-4

#include  <stdio.h>

#include  <string.h>

#define MAX_LEN 10 / * Maximum string length * /

#define N 150 / * number string * /

void SortString(char *ptr[], int n);

int main ()

{

         int    i, n;

         char name [N] [MAX_LEN]; / * define a two-dimensional array of characters * /

         char * pStr [N]; / * pointer array defined character * /

         printf("How many countries?");

         scanf("%d", &n);

         getchar (); / * read the input buffer walking carriage return * /

         printf("Input their names:\n");

         for (i=0; i<n; i++)  

         {

                  pStr [i] = name [i]; / * make pStr [i] point to a two-dimensional array of characters name of the i-th row * /

                  gets (pStr [i]); / * input to the i-th pStr string [i] at the memory * /

         }

         SortString (pStr, n); / * String sorted lexicographically * /

         printf("Sorted results:\n");

         for (i=0; i<n; i++)                 

         {

                  puts (pStr [i]); / * output the sorted string of n * /  

         }

         return 0;

}

/ * Function: a function pointer array for the parameter exchange method employed to achieve a string lexicographically sorted * /

void SortString(char *ptr[], int n)

{

         int    i, j;

         char * temp = NULL; / * address value is exchanged by the string, it is defined as a pointer variable * temp /

         for (i=0; i<n-1; i++)                             

         {

                  for (j = i+1; j<n; j++)

                  {

                          if (strcmp (ptr [j], ptr [i]) <0) / * pointer to a string of exchange * /  

                          {

                                   temp = ptr[i];             

                                   ptr[i] = ptr[j];

                                   ptr[j] = temp;                               

                          } 

                  }   

         } 

}

 

/ * This program, the string is stored in a two-dimensional array of characters in the name, and nothing has changed

         String in which the actual physical storage space in the storage position i.e. after execution SortString () does not change

         However, each pointer points to a string array element changed before and after the change of the sort that such changes only the pointers to the sort of the elements in the array * /

 

/ * Physical ordering: storage position achieved by moving the string in the actual physical storage space ordering

Sort index: the index address by moving the string (pointers) to achieve sorting

With respect to the two-dimensional array implemented using a physical method of sorting, using an array of pointers to achieve a higher index of some sort of efficiency of program execution * /

 

// array of pointers for indicating the command line parameters

// L11-5

#include <stdio.h> // the program's file name is echo.c, the executable file compiled connection named echo.exe

Is defined int main (int argc, char * argv []) // main arguments () function

// 1st argc parameter is declared as an integer variable for storing the number of command line arguments

// second parameter is declared as a pointer argv array, for receiving a command-line parameters

// Since all the command line parameters are treated as a character string, where each element so argv array of character pointers point to the command line parameters

{

         int  i;

         printf("The number of command line arguments is:%d\n", argc);

         printf("The program name is:%s\n", argv[0]);

         if (argc > 1)

         {

                  printf("The other arguments are following:\n");

                  for (i=1; i<argc; i++)

                  {

                          printf("%s\n", argv[i]);

                  }

         }

         return 0;

}

 

//operation result

Windows PowerShell

Copyright (C) Microsoft Corporation. all rights reserved.

 

PS C:\Users\lenovo> Desktop\echo.exe programming is fun

The number of command line arguments is:4

The program name is:C:\Users\lenovo\Desktop\echo.exe

The other arguments are following:

programming

is

fun

 

/ * Command-line parameter is useful, especially in a batch command using the more widely

For example, passing the name of the program file to be processed to a program through command-line parameters, options specified command can also be used, etc.

When the program does not require command-line arguments, generally in the back of the main braces keyword void the function main () is declared as no parameter * /

 

// C program's memory image

/ * Read only memory area: a machine code and stored program read-only data string constants

Static memory areas: global variables in the program and static variables

Heap: return address operation information, a function parameter, and the current status of the CPU local variables stored program when a function call

Stack: free store, program C using dynamic memory allocation function to use it * /

 

// memory allocation in C language program variables

/ * Static memory allocation from

Allocated on the stack

Allocated from the heap * /

 

// Pointer is important

/ * Pointer to provide means to modify variable values ​​as a function of

Pointer support for dynamic memory allocation system C

Pointer support for dynamic data structure

Improve the efficiency of certain pointer subroutine * /

 

/ * Pointer to define dynamic arrays is another important application of the pointer other than the parameter as a function of

Dynamic memory allocation refers to a method to allocate memory at runtime variable

Suitable for a variable number of required memory space in the program run, namely at run time to determine how many bytes of memory to be used to store the situation data * /

 

// dynamic memory allocation function (at the beginning of the program requires the header <stdlib.h> included in the source program when used)

/* malloc()

Memory allocation for a plurality of bytes, returns a pointer to the first memory address

If the system can not provide enough memory unit, the function returns a NULL pointer

void *malloc(unsigned int size);

 

void * generic pointer or pointer is untyped pointer, i.e. a pointer variable declared, but it may specify which type of data point groups

To so function call returns a value to the pointer, the base should be in accordance with the pointer type, with a strong way transfer return pointer value into the desired type strongly

 

calloc()

For allocating a plurality of contiguous storage space for the same type of data item assigned to 0 and returns the first address

void *calloc(unsigned int num, unsigned int size);

 

free()

Release dynamics apply to the system memory space by pointer p points, no return value

void free(void *p);

The only parameter p address given address only () return () when the application memory by malloc Ho calloc

 

realloc()

For changing the size of the originally allocated storage space

void *realloc(void *p, unsigned int size);

 

Since the memory cell obtained by the dynamic memory allocation is unknown, it can only be referenced by a pointer variable

So once we changed the pointer to the memory of the original allocation and data along with it was lost

Therefore, do not easily change the value of the pointer variable * /

 

// L11-6

#include  <stdio.h>

#include  <stdlib.h>

void InputArray(int *p, int n);

double Average(int *p, int n);

int main ()

{

         int  *p = NULL, n;

         double aver;

         printf("How many students?");

         scanf ( "% d", & n); / * number of students input * /

         p = (int *) malloc (n * sizeof (int)); / * allocate memory to the system * /

         if (p == NULL) / * pointer before use to ensure a non-null pointer, the program run ends when p is NULL pointer * /

         {

                  printf("No enough memory!\n");

                  exit(1);

         }

         printf("Input %d score:", n); 

         InputArray (p, n); / * input student achievement * /         

         aver = Average (p, n); / * average is calculated * /

         printf ( "aver =% .1f \ n", aver); / * output average * /

         free (p); / * release the system memory to the application * /

         return 0;

}

/ * Pointer variable declared as a parameter, the value of the input array elements * /

void InputArray(int *p, int n) 

{       

         int i;

         for (i=0; i<n; i++)

         {

                  scanf("%d", &p[i]);        

         }       

}

/ * Pointer variable declared as a parameter, the average value calculation array elements * /

double Average(int *p, int n) 

{

         int i, sum = 0;

         for (i=0; i<n; i++)

         {

                  sum = sum + p[i];           

         }

         return (double)sum / n;      

}

 

// L11-7

#include  <stdio.h>

#include  <stdlib.h>

void InputArray(int *p, int m, int n);

double Average(int *p, int m, int n);

int main ()

{

         int  *p = NULL, m, n;

         double aver;

         printf("How many classes?");

         scanf ( "% d", & m); / * number of classes input * /

         printf("How many students in a class?");

         scanf ( "% d", & n); / * class size input * /

         p = (int *) calloc (m * n, sizeof (int)); / * allocate memory to the system * /

         if (p == NULL) / * pointer before use to ensure a non-null pointer, the program run ends when p is NULL pointer * /

         {

                  printf("No enough memory!\n");

                  exit(1);

         }

         InputArray (p, m, n); / * * student performance input /         

         aver = Average (p, m, n); / * average is calculated * /

         printf ( "aver =% .1f \ n", aver); / * output average * /

         free (p); / * release the system memory to the application * /

         return 0;

}

/ * Parameter declared to point to the two-dimensional array column pointer, array element value input * /

void InputArray(int *p, int m, int n)  

{       

         int i, j;

         for(i = 0; i<m; i++)        /* m个班 */

         {

                  printf("Please enter scores of class %d:\n", i+1);

                  for (j = 0; j <n; j ++) / * * class students n /

                  {

                          scanf("%d", &p[i*n+j]);        

                  }

         }

}

/ * Pointer variable declared as a parameter, the average value calculation array elements * /

double Average(int *p, int m, int n) 

{

         int i, j, sum = 0;

         for(i = 0; i<m; i++)       /* m个班 */

         {               

                  for (j = 0; j <n; j ++) / * * class students n /

                  {

                          sum = sum + p[i*n+j];               

                  }                           

         }

         return (double)sum / (m*n);        

}

 

// common memory errors and countermeasures

/ * Illegal memory access

Persistent memory leaks lead to insufficient system memory

 

Memory allocation was unsuccessful on the use of

Memory allocation successful, but on the use of uninitialized

Memory allocation successful, also initialized, but happened to use cross-border

Forget the free memory, resulting in a memory leak

After releasing the memory still continue to use * /

 

// field guide

/ * Pointer operations beyond the scope of the variables

Uninitialized pointer variable

Pointer variable points after free dynamic memory is not set to NULL * /

//solutions

/ * Do not address local variables as the return value of the function's return

In the definition of indicator variables simultaneously initialize

Try to malloc () function of concentration at the inlet, free () function of the concentration at the outlet * /

 

// buffer overflow attacks

/ * Use strncpy (), strncat () like "n group" string manipulation functions, string manipulation is restricted by increasing the maximum length of a parameter, prevent the occurrence of buffer overflow

 

As long as it is checked prior to use arguments passed in from the outside

Carefully prevent cross-border pointer

Should not prevent access code access memory

It is not difficult to resist buffer overflow attacks * /

 

Guess you like

Origin www.cnblogs.com/dingdangsunny/p/11254278.html