Summarized some common pointer error-prone issues (1), pointer FAQs

Source: Internet
Author: User

Summarized some common pointer error-prone issues (1), pointer FAQs
1. Recognize pointers

1.1 pointer and memory

After the C program is compiled, it uses the memory in three forms:

1) Static/global memory

Here are static/Global declared variables. These variables are allocated from the start of the program until the program ends.

All functions can access global variables. The scope of static variables is limited to the functions that define them.

2) Automatic Memory

These variables are declared within the function and created only when the function is called. Their scope is limited to the function,

The declaration period is limited to the execution time of the function.

3) dynamic memory

The memory is allocated to the heap and can be released as needed. It does not disappear until it is released. Pointer Reference allocated memory, Scope

It is limited to the pointer that references the memory.

    Array and pointer:

1. When creating an array, you need to know the length of the array, which will limit the number of elements contained in the linked list.

2. There are no restrictions on pointers. New nodes can be dynamically allocated as needed. The malloc and free functions allocate and release dynamic memory.

Tips:

1.Read the pointer declaration.

Const int * pci // pci is a pointer variable pointing to an integer constant.

2. It is difficult to display the pointer values in a consistent manner on different platforms. One way is to convert the pointer (forced) to the void pointer and display it with the % p/% o/% x format specifier.

Printf ("Value of pi: % p \ n", (void *) pi );

The void pointer is a common pointer used to store any data type reference. Any pointer can be assigned to the void pointer, which can be converted to the original pointer type.

Void is only used as a Data Pointer and cannot be used as a function pointer.

3. the pointer is declared as global/static. It is initialized to NULL when the program is started.

1.2 pointer Operator

Direct and indirect reference

Pointers can be referenced in different levels indirectly. Double pointer **.

char *titles[]={"ajj","bbs","klc"};        char **bestbooks[2];        char **english[1];          bestbooks[0]=&titles[0];          bestbooks[1]=&titles[1];          english[2]=&titles[2];

Constants and pointers

2. C dynamic memory management malloc/realloc/calloc/free

 Malloc allocates Bytes/sizeof (bytes)

Memory leakage: the memory address is lost. The free function should be called but not called.

 

Lost pointer

3. pointer and function pointer function/function pointer/program stack/heap

  Program stack (the program stack usually occupies the lower part of the region, the stack is the upper part, the stack grows up, and the stack grows down)

One of the main reasons for passing data with pointers is that the function can modify data.

 4. function pointers and pointer Functions

 

 

It is easier to declare a type definition for the function pointer. The type is defined as follows:

Typedef int (* funcptr) (int );

Funcptr fptr2;

Fptr2 = square;

......

# Include <iostream> using namespace std; int main () {int square (int num); int (* fptr1) (int ); // similar to the definition variable typedef int (* funcptr) (int); funcptr fptr2; fptr2 = square; int n = 5; fptr1 = & square; // you can replace it with fptr1 = square, and the function name indicates the function entry address cout <"5 square is" <fptr1 (n) <endl; cout <"5 square is" <fptr2 (n) <endl; return 0;} int square (int num) {return num * num ;}

To pass the function pointer, you only need to declare the function pointer as a function parameter (form parameter.

#include<iostream>using namespace std;  int add (int num1,int num2)    {    return num1+num2;    }int sub(int num1,int num2)    {        return num1-num2;    }typedef int (*fptr)(int,int);    int compute(fptr operation, int num1,int num2)    {        return operation(num1,num2);    }        int main(){    cout<<compute(add,5,8)<<endl;    cout<<compute(sub,5,8)<<endl;    return 0; } 

To return a function pointer, you must declare the return type of the function as a function pointer. (Note the remarks ////)

#include<iostream>using namespace std;  int add (int num1,int num2)    {    return num1+num2;    }    int sub(int num1,int num2)    {        return num1-num2;    }    typedef int (*fptr)(int,int);    int compute(fptr operation, int num1,int num2)    {        return operation(num1,num2);    }//////////////////////////////////////////////    fptr select(char opcode)    {        switch(opcode)        {            case '+':return add;            case '-':return sub;        }    }        int evalute(char opcode,int num1,int num2)    {        fptr operation=select(opcode);        return operation(num1,num2);    }    ///////////////////////////////////////////////    int main(){    cout<<evalute('+',5,8)<<endl;    cout<<evalute('-',5,8)<<endl;    return 0; } 

You can use the function pointer array to select the function to be executed based on certain conditions. You only need to declare these function pointers as arrays. Definition:

# Include <iostream> using namespace std; int add (int num1, int num2) {return num1 + num2;} int sub (int num1, int num2) {return num1-num2 ;} typedef int (* fptr) (int, int); int compute (fptr operation, int num1, int num2) {return operation (num1, num2 );} /// // returns the function pointer /////////////// //////// fptr select (char opcode) {switch (opcode) {case '+': return add; case '-': return sub;} int evalute (char opcode, int num1, int num2) {fptr operation = select (opcode); return operation (num1, num2 );} /// // use the function pointer array /////////////// /// // typedef int (* operation) (int, int); operation operations [128] = {NULL}; void initializeopArray () {operations ['+'] = add; operations ['-'] = sub ;} int evaArray (char opcode, int num1, int num2) {fptr operation; operation = operations [opcode]; return operation (num1, num2 );} //////////////////////////////////////// /// // int main () {initializeopArray (); cout <evalute ('+', 5, 8) <endl; cout <evalute ('-', 5, 8) <endl; cout <evaArray ('+', 5, 8) <endl; cout <evaArray ('-', 5, 8) <endl; return 0 ;}

Summary: Understanding Program stacks and stacks helps you gain a deeper understanding of how programs work and pointer behavior.

Note: The code in this article is compiled by the Dev C ++ compiler.

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.