pointer in c

Everyone knows the magic of C is pointer.So i want to write about pointer,just experience no grammer.

what is pointer

Now I guess you should know the define of pointer,so i will show the detail.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


//now we should know the size of type

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]
return 0;
}

How to use pointer in function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

#include <stdlib.h>

//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;
}

void print(int* a,int* b){
printf("first number:%dn",*a);
printf("second number:%dn",*b);
}

int main(){
int a = 1;

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

I will keep updating.