Title: Pointers and Arrays
1Pointers and Arrays
- An array is an indexed set of variables of a
given data type. - Essentially, both pointers and array identifier
are memory addresses. - Array name, in particular, is the address of the
first element.
(ip)
(ip1)
(ip2)
char a8 char ip ipa /ipa0/
a
a0
a1
a7
(a1)
a
ip0
ip1
ip7
2Pointers and Arrays
char a8 int ip ipa /ipa0/
ip
ip1
a
a0
a1
ip0
ip1
3Pointer and Arrays
- Difference
- a pointer is a variable, array name is not, you
may consider an array as a constant pointer. - char pa
- char line8ABCDE
- paline/RIGHT/
- pa/RIGHT/
- linepa/WRONG/
- line/WRONG/
- paABCDE /RIGHT/
- lineABCDE /WRONG/
4Address Arithmetic
- Pointers can have arithmetic operations!
int ip1, ip2, a8 char ip3 ip1
a7 ip2 a0 Then all the following are
legal! ip1ip2 /assignment of pointers of the
same type/ ip2 1 /adding or subtracting a
pointer and an integer/ ip1 - ip2 /subtracting
two pointers to members of same
array/ ip1 NULL /comparing to zero or
NULL/ ip2NULL /assign to NULL/ ip1 gt ip2
/comparing two pointers to members of same
array/
5Address Arithmetic
- int ip1, ip2, a8
- char ip3
- ip1 a7
- ip2 a0
- Then all the following are illegal!
- ip3 ip1 /Warning different type/
- ip1 ip2 /pointers can not be added together/
- ip1ip2 /pointers can not use multiply/
- ip10x10 /pointers can not and a constant/
- ip1 3.24 /pointer can not add with
non-integers/
6Character Pointers
- char sabcde /RIGHT/
- char m end /RIGHT/
- char t
- mget /WRONG/ why?
- sdfdg /RIGHT/
- ma /RIGHT/
- s a /WRONG/
- ta /WRONG/ why?
7Memory Allocation
- char x
- int y
- xmalloc(sizeof(char))/xmalloc(1)/
- ymalloc(sizeof(int))/ymalloc(4)/
- y1
- xa
8Memory Interface
- Interfaces from ltstdlib.hgt
- malloc void malloc(int size)
- malloc allocates size bytes of memory and return
a pointer to this memory. No initialization is
performed on the memory. - calloc void calloc(int num, int size)
- calloc allocates memory for num items of size
bytes. This memory is initialized to be zero. - free void free(void ptr)
- free releases the memory allocated at ptr for
reuse. Does nothing if ptr is NULL. - Miscellaneous
- memset void memset(void ptr, int c, int size)
- memset sets size bytes memory allocated at ptr
with c. - bzero void bzero(void ptr, int size)
- bzero sets size bytes memory allocated at ptr to
zero.
9Memory Allocation
- Where we have dealt with memory issues
- Return characters strings It is incorrect to
return a local char array.
char encode(int x) char temp4
temp0A x return temp / WRONG
/ char encode (int x) char
tempmalloc(4) temp0Ax return
temp/RIGHT/
buff256
malloc(256)
10Memory issues
- Memory Leak
- Every user level program, by its startup, will
have a heap which holds all the constants and
global variables, as well as all the memory
allocated through "malloc". By the time the
program finishes, the operating system will get
back - all these memory. Of course, it doesn't
mean that you can freely malloc spaces without
free them. This will cause problem when your
program is very large. You will run out of heap
space. This is what we called memory leak. - Pointer aliases
- int a malloc(4 sizeof (int))
- Â int b a
- Â free(b)
- Â a 3/WRONG/
11Rules
- Do NOT dereference a pointer before it is
assigned a memory area - char s
- sa/WRONG/
- Dereference only pointers with type than void
- void amalloc(100)
- a12/WRONG, Complier Complains/
- Always free the memory you allocated
- Be cautious of your pointer aliases
- Initialize your pointers with NULL
12Multi-dimension Arrays
- char a34
- Complier will reserve a consecutive memory for
this array
a00 a10 a20
int a543 aijk is equivalent to
(a00043i3jk)
13Pointer Array
- Pointer Arrays should be initialized with
addresses, such as - char ip3, a34
- ip0 a00
- ip1 a10
- ip2 a20
- Or
- char monthname
- "Illegal Month","January","February","March","Oth
ers" -
14Sample Usage -- command-line arguments
- A typical usage, command line arguments
- includeltstdio.hgt
- int main (int argc, char argv)
-
- int i0
- while (ilt argc)
- printf(Argument d s\n,i, argvi)
-
- return 0
-
- gcc o prog sample.c
- prog my argument list
- Argument 0 prog
- Argument 1 my
- Argument 2 argument
- Argument 3 list
15Pointer Arrays
- Comparisons with multi-dimensional arrays
int ip3, a34, i0 ip0
a00 ip1 a10 ip2
a20 What if I want to claim an pointer
array which itself has variable length?
16Pointer to Pointers
- We can use
- int ip
- How to allocate memory for such a pointer
- which points to pointers ?
17Memory Allocation for pointer to pointers
- char line
- int i
- line (char )malloc (100sizeof(char ))
- for (i 0 ilt100i)
- linei (char )malloc (8)
- 81004001200 bytes!
18User-defined data types
- Structures
- A structure is a user-defined data type. It
consists of a set of elements - A collection of other data types
- Used a lot for organized complex data structures
- Unions
- A combination of various different types
19Basic Structures -- Declaration
- struct tag members variables
- A structure declaration defines a type.
- Type declaration with tag
- struct point
- int x
- int y
-
- Used later for variable declaration
- struct point a, b
- Also valid
- struct point
- int x
- int y a, b
- struct int x int y a, b
20Basics of Structures
- A structure member or tag can share name with an
ordinary (non-member) variable - The same member names may occur in different
structures - Structure declaration is just to define a
template, it does not reserve storage.
21Structure Usage
- Member access
- struct point a
- a.x and a.y
- Hierarchical structure
- struct members can be of any data type, including
a struct - nested structs
- struct rect
- struct point low_left /WRONG point
low_left/ - struct point top_right
- box
- box.low_left.x
- Initialize structure variable
- struct point int xint y pt, a
- struct point pt1320,200
- struct point a1 pt1 /Need to be of the same
type./
22Structure Arithmetic
- initialization, copy/assignment
- struct point middle50,50/RIGHT/
- struct point middle
- middle50,50 /WRONG/
- You should use function as assignment.
- struct point makepoint(int x, int y)
-
- struct point temp
- temp.xx
- temp.yy
- return temp
-
- struct point middle
- middlemakepoint(50,50)
- cannot be used to test for structure
equality. - struct point x
- struct point y
- if(xy) ./WRONG/
-
23Structure Pointer
- struct point pt
- pt is the structure
- (pt).x,(pt).y are the members
- pt.x /since pt is pointer, so WRONG here/
- How to use pointers to access members?
- pt-gtx, pt-gty
24Structure Pointer
- We can use to get address of a structure and
assign it to a pointer, thus make the pointer
point to the structure - struct rect r,rpr
- r.low_left
- rp-gtlow_left
- r.top_right
- rp-gttop_right
25Structure Pointer
- struct
- int length
- char string
- p
- p-gtlength /add 1 to p-gtlength/
- (p)-gtlength /access length of next structure
if it exists/ - p-gtlength /access p-gtlength, p/
- p-gtstring /fetch whatever string points to/
- p-gtstring /increment string after accessing
whatever string points - to/
- (p-gtstring) /increment whatever string points
to/ - p-gtstring /increment p after accessing
whatever string points to/
26Structure Array
- A new declaration of rectangle
- struct point int x, int y pt2
- Students in class c459.21
- struct student
- char name10
- int score
-
- struct student c45930
27Structure Array
- Calculate average score
- int average( struct student p, int n)
-
- int i, total 0
- for (i 0 i lt n p, i)
- total p-gtscore
-
- return (total/n)
int main() int result struct student
c459 John, 90, Adam, 80,
resultaverage(c459,
sizeof(c459)/sizeof(struct student)) return
0
28Structure Array
- Calculate average score
- int average (struct student c , int n)
-
- int i, total 0
- for (i 0 i lt n i)
- total ci.score
-
- return (total/n)
int main() int result struct student
c459 John, 90, Adam, 80,
resultaverage(c459,
sizeof(c459)/sizeof(struct student)) return
0
29Unions
- A combination of various different types
- Syntax like structures, but different
implications - The size of a union is the maxim of all
- The size of a struct is at least the combination
of all - Same memory content with different representation
union addr char cp int ip int
value
union num_rep int x short s char
c
30More on user defined data types
- sizeof
- Safe way to tell the size of structures or unions
- struct s2
- int x
- char c
- short s
-
- typedef
- Specify a new name for the same type
- typedef int Length
- Length len,maxlen
- Can be used to wrap a structure declaration for
convenience - typedef struct point int x int y point
- point x /struct point x/