Examples of enumeration and Pointers in C
- 2020-05-27 06:47:03
- OfStack
An example of enumeration and Pointers in C
In summary 1, define an enumeration, using the typedef enum keyword, such as typedef enum{Red,Green,Blue} Color3;
The conversion from enumeration to value, if no representative value is specified, is calculated from 0, such as Color3 c=Red; printf (" % d c); 0 is displayed unless specified as typedef enum{Red=3,Green=5,Blue=10} Color3;
As for the definition of type pointer, * is added to the left of the variable name to indicate that the variable is only a null pointer. If the initial value is needed, it can only be =0 or =NULL(NULL is also 0). The following statement must actually assign a new address or apply for memory before it can be used.
The use of Pointers is also very simple, such as int i=10; * pi = 0; The defined pi pointer is used to refer to pi if pi is used to refer to pi, and *pi is used to refer to the specific value of pi.
Such as:
int i=10, *pi=0;
pi= &i ;// & It's taking the address
*pi+=5;
printf("%d",*pi); // 15
printf("%d",i); // because pi Point to the i The address of the ,*pi changed ,i Also follow change , Is also 15
OK, if the pointer wants to apply for a new memory, you can use malloc, such as:
#include <malloc.h>
...
int *p=0;
p=(int*) malloc(sizeof(int)); // Here for p Pointer to the application 1 Block of actual memory
*p=12345; // for p The memory assignment referred to
printf("%d",*p); // 12345
free(p) ;// Free memory
OK, then how to transfer pointer parameters, as follows:
void testP(int *p){
*p+=100;
}
void main(){
int i=10;
testP(&i);
testP(&i);
printf("%d", i): // What do you think it is ?
}
If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!