c Pointers and memory

Source: Internet
Author: User

c Pointers and memory

  Pointers are important construction types in C/s + + , and pointers give C + + Programs The ability to directly access and modify memory. Many of the most important applicationsin C + + , such as compilation,OS, and embedded development, are dependent on this capability.

The von Neumann system's computer memory stores instructions and data, which we can abstract into the instruction area and data area (which is, of course, much more complex). The data area contains stacks and Heaps (heap) areas, data from the stack is managed by the compiler, and the heap data is managed by the programmer.

Because the instruction also exists in memory, the function also has an address (pointer) in memory. function pointers can dynamically select called functions at run time relative to the function name, which is an important basis for C + + to implement dynamic polymorphism.

Onebasic usage of pointers

A pointer is a constructed type, and all basic types and structs have their own pointers. The pointer contains the first address (that is, the value of the pointer) and the type of the object to the two-part information, so the pointer is not strictly equivalent to the address.

Do not use an uninitialized pointer otherwise it will cause a serious run-time error, fortunately the operating system's memory management can ensure that the operating system itself and other processes stable, but your program will definitely quit unexpectedly. The type of pointer is important, and a pointer to a struct can use a ptr--- member expression to access a member after initialization, but uninitialized or void The pointer will cause an error or warning.

As mentioned inC Programming Basics, square brackets ([]), pointers (*) These symbols have different meanings in declaration statements and execution statements, but still have some characteristics of operators.

That is, the pointer (*), the square brackets ([]) , and the function call ( the parameter table ) in the declaration statement You can think of a flag that marks an identifier as a special type, and when there are multiple flags in the same declaration statement, they determine the type of the declaration in the order in which they are solved:

(1) Basic statement:

"Int *p;" declares pointer p(note not *p),*p represents the data it points to.

"Int p[m];" Declares a one-dimensional array p with a length of M .

"Int p[m][m];" declares mxm two-dimensional array p.

(2) Composite declaration:

"Int **p" declares that p is a double pointer (not **p), then *p is a pointer,**p is a data object.

"Int *p[m]" declares an array of pointers, and the elementary operator combines right-to-left first declares an array, and then declares the array element type as a pointer.

"Int *fun (...) "Declares a function that returns a pointer, right-to -left first declares fun as a function, and then declares the return value type as a pointer."

"Int (*ptr) (...) the Declaration ptr as a function pointer, right-to-left first declares that this is a function, (*ptr) declares that this is a function pointer. When using a function pointer, simply use (*ptr) instead of the letter name, for example:

   Qsort Library functions use function pointers as predicate functions

#include <stdio.h>#include<stdlib.h>intTellConst void*a,Const void*b) {intx, y; X= *(int*) A; Y= *(int*) b; returnX-y;} intMainvoid) {   intI, M, a[ the] = {0 }; int(*TP) (Const void*a,void*b); TP=Tell ; scanf ("%d", &m);  for(i =0; I < m; i++) {scanf ("%d", &A[i]); } qsort (A, M,sizeof(int), TP);  for(i=0; i<m;i++) {printf ("%d", A[i]); } printf ("\ n"); return 0;}

Pointers as function parameters can be used to implement a call to address, the following is the simplest to exchange two number of programs:

#include <stdio.h>intSwapint*PA,int*pb) {             intT; T= *pa;//*pa is "a" itself*PA = *PB; *PB =T; return 0; }    intMainvoid) {  intb; scanf ("%d%d",&a,&b); Swap (&AMP;A,&AMP;B);//using &a as a ptr to "a"printf ("%d%d\n", A, b); return 0; } 
• Regular pointers

"const int * PTR; "" int const * PTR; pointer to a constant object

"int * Const PTR = &a; "Point to a pointer that cannot be changed, must be initialized

"const int * Const PTR = &a; "" int const * Const PTR; "

Pointers to objects that cannot be changed;

A pointer to a regular object near the base type marked with a *, and a pointing constant near the cursor.

Twoarrays and their storage

1. One-dimensional arrays

The way the array is declared is described above:

(1) declares a length of 8 int array arr int arr[8]; "

(2) The length of the array must be a constant integer , can't be Const Object " const int n = 8;int arr[n]; "; can be an enumeration element but not an enumeration object, usually using a literal value or a macro as the length" #define N 10 ";

(3) array subscript from 0 Start (not 1 );

(4) square brackets ( [] ) You can access a member of the array, " arr[i];arr[0]; ".

An array defined within a function is not automatically initialized, and an array defined outside the function is automatically initialized to 0(or Equal value). When you define an array at the same time within a function, the uninitialized variable is automatically initialized to the 0 value "int arr[8] = {n/a}; "This feature is used to initialize all arrays to 0 value, " int Arr[8] = {0}; ". You do not need to specify an array length when initializing all elements, i.e. "int arr[] = {.}; "and" int arr[2] = {.} "equivalent.

2. High-dimensional arrays

We can understand a high-dimensional array as an array of arrays, that is, the elements of a high-dimensional array are one-dimensional arrays of lower dimensions. Because the array name is its first address, the elements of the high-dimensional array are the first addresses of the low-dimensional arrays. Take the two-dimensional array as an example and use a[i]<=>* (a+i) to expand

A[I][J] <=> * (a[i]+j) <=> * (* (a+i) +j)

The unit of I is the length of a one-dimensional array, andthe unit ofJ is the length of the base type. When deduced, will [] Expand, add a & is less one *.

* (a+i) +j <=> a[i]+j <=> &a[i][j]

There are two forms of initialization of high-dimensional arrays. First, the elements are understood as arrays, and the initial values of each array are enclosed in curly braces, and they are surrounded by another brace as an element. A high-dimensional array is linearly stored in memory and can be initialized as a one-dimensional array based on the order in which it is stored in memory. In both of these ways, elements that are not assigned are automatically assigned 0. When assigning values to all elements, the length of the first dimension can be omitted from the compilation system, and the other dimensions cannot be omitted.

3.

An array is a contiguous memory space, and the array name can be thought of as a constant pointer (it is not allowed to change points). From the array implementation, the subscript starts from 0 and is very natural.

c the method of processing the subscript is to convert it to an address, a[i] and * (a+i) unconditionally equivalent.

Third,Dynamic memory Management1.Allocating Memory(Memory alloc):

"Void *malloc (unsigned int size);" (Common)

(1)   Allocates a size of size size is an unsigned integral type (negative numbers are not allowed). The return value of the function is the address of the first byte of the allocated region. Returns a null pointer If the function does not execute successfully (such as insufficient memory space)

(2) A void pointer type cannot be interpreted as pointing to any type , but as a pointer to data of an indeterminate type. Apply the assign operator (cast) to Change the void pointer to a specific type pointer, andthesize parameter applies The sizeof () operator evaluates to avoid errors , such as the size of the struct is not strictly equal to the sum of all member sizes and improves program portability. For example:

"int * ptr = (int *) malloc (sizeof (int) * N);"

Declares that ptr points to a length of n continuous int space (actually a length of N int array).

2.Allocating contiguous space:

"Void *calloc (unsigned n,unsigned size);"

allocating n contiguous spaces of size to a dynamic store can be used to hold an array.

3.Freeing Memory(free):

"Void free (void *p);"

Releases the dynamic space pointed to by the pointer variable p , with no return value. For example: "Free(PTR); "

4. Reallocate Memory(realloc):

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

change the amount of dynamic space that p points to size .

c Pointers and memory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.