-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathpointer.c
73 lines (57 loc) · 1.59 KB
/
pointer.c
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
# Pointer
Pointers contain addresses of variables instead of the value.
Using the dereference operator `*`, you can get the value from the address.
*/
#include "common.h"
int main(void) {
int i;
int *pi, *pi2;
/* BAD */
/* you are modifying some random piece of memory!!!! */
/* must declare like that: multiple stars */
/**pi = 7;*/
pi = &i;
*pi = 1;
assert(i == 1);
assert(*pi == 1);
i = 2;
assert(i == 2);
assert(*pi == 2);
printf("(void*)pi = %p\n", (void*)pi);
printf("(void*)(pi+1) = %p\n",(void*)(pi+1));
/* OK: implicit conversion * -> int: */
pi2 = pi + 1;
printf("(void*)(pi2-pi) = %p\n", (void*)(pi2-pi));
assert(pi2 - pi == 1);
/* ERROR: incompatible pointer type */
/*float *fp = &i;*/
/* OK: works with explicit cast: */
float *fp = (float *)&i;
/*
# Single line multiple pointer declaration
You must put an asterisk for each pointer, or they are not taken to be pointers!
This is not very intuitive since the asterisk is part of the type, not of the variable.
*/
{
/* Correct */
{
int i, *ip ;
ip = &i;
}
/* ERROR: ip2 is not a pointer, but an int! */
{
/*int i;*/
/*int *ip, ip2;*/
/*ip = &i;*/
/*ip2 = &i;*/
}
}
/*
# Two varibles with the same address
Impossible:
http://stackoverflow.com/questions/15590727/same-address-of-two-variables
Possible in C++ with references `&`.
*/
return EXIT_SUCCESS;
}