void printSize(){ printf("%dn",sizeof(char)); //1 printf("%dn",sizeof(int)); //4 printf("%dn",sizeof(long)); //4 printf("%dn",sizeof(unsigned long)); //4 char a = '1'; int b = 1; long c = 1; printf("%dn",sizeof(&a)); //8 printf("%dn",sizeof(&b)); //8 printf("%dn",sizeof(&c)); //8 return; }
int main(){ printSize(); int a = 1; int* b = &a; printf("%dn",&a); //&a is address printf("%dn",*b); //*b is value int c[3] = {1,2,3}; printf("%dn",c); //c is address printf("%dn",*c); //*c is the same as c[0] printf("%dn",*(c+1)); //*(c+1) is the same as c[1] return0; }
//in function,a and b as formal parameter,so compiler will //create temporary space to store a and b.So you change //variable value is temporary,it only uesful in the action //scope. void swap1(int a,int b){ int tmp = a; a = b; b = tmp; return; }
//in function,we delivery variable's address.We call it as //pointer.In fact,any address would point to variable.If we //change value by pointer.Finally,the variable will be changed void swap2(int* a,int* b){ //this function can not swop variables. int* tmp = a; //because tmp is address,so if variable's value is changed *a = *b; //the value will be changed which address is same. *b = *tmp; return; }
void swap3(int* a,int* b){ //this function is right. int tmp = *a; *a = *b; *b = tmp; return; }
int b = 2; swap1(a,b); print(&a,&b); //a = 1;b = 2; int a = 1; int b = 2; swap2(&a,&b); print(&a,&b); //a = 2;b = 2; int a = 1; int b = 2; swap3(&a,&b); print(&a,&b); //a = 2;b = 1; }
How to use pointer in struct
Ok,i define a struct.
1 2 3 4
typedef struct ListNode{ int val; struct ListNode* next; };
How to use malloc?
malloc() is a function to apply for space.If you want to create a new variable then assignment data.You need to use malloc(),but sometimes you just want to get an address,so you only apply for a variable.
1 2
ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode)); //to apply for space to save data ListNode* l = p; //l is a address to save the begining of list
近期评论