You are on page 1of 32

Pointers,Arrays,MultidimensionalArrays

Pointersversusarrays
Lotsofsimilarities

Howtodealwith2D,3D,multidimensionalarrays
(for storing matrices and other 2D or 3D data!)
(forstoringmatricesandother2Dor3Ddata!)

CSE251Dr.CharlesB.Owen
ProgramminginC

Review:Pointers
Address

Pointersarevariablesthat
storememoryaddresses

0xeffffa94
0xeffffa98

Memory
15
0xeffffa94

int a
a =15;
15;
int *b=&a;
printf(%x%x%d\n,b,&b,*b);
// prints effffa94 effffa98 15
//printseffffa94effffa9815

CSE251Dr.CharlesB.Owen
ProgramminginC

Name

a
b

int number;
int *ptr =&number;

Read&
as at
as
at

printf(Enteraninteger:);
scanf(%d
scanf(
%d , &number);
printf(Enteranotherinteger:);
scanf(%d, ptr);

Usingpointersin
scanf function
Donthavetoput
&beforeptr.Its
already an at
alreadyan
at .

printf(Number=%d,*ptr =%d\n,number,*ptr);
Exampleoutput:

CSE251Dr.CharlesB.Owen
ProgramminginC

int multiply(int *,int);

Passingpointers
(addresses) to
(addresses)to
functions

int main()
main()
{
int number=3;
int *ptr =&number;
&n mber;
printf(1:%d\n,multiply(&number,2));
printf(2:%d\n,multiply(ptr,3));
}
int multiply(int *a, int factor)
{
return(*a) *factor;
}

CSE251Dr.CharlesB.Owen
ProgramminginC

Review:Arrays
Anarrayisacontiguouschunkofmemorytostore
multiplevalues
int grades[]={74,59,95,85,71,45,99,82,76};
0xeffffa00 0xeffffa04 0xeffffa08 0xeffffa0c 0xeffffa10 0xeffffa14 0xeffffa18 0xeffffa1c 0xeffffa20

grades

74

59

95

85

71

45

99

82

76

index

CSE251Dr.CharlesB.Owen
ProgramminginC

int sumArray(int [],int);

Passingarraysto
functions

int main()
{
int list[]={1,2,3,4};
printf(Sum=%d\n,sumArray(list ,4));
}
int sumArray (int list[],int arraySize)
{
int sumvalue =0;
for(int i=0;i<arraySize;i++)
sumvalue +=list[i];
+= list[i];
returnsumvalue;
}

CSE251Dr.CharlesB.Owen
ProgramminginC

ArrayName
Thearraynameisa
list
pointertothefirst
elementofthearray
l
t f th

ffe2de0c

ffe2de10 ffe2de14 ffe2de18

[0]

[1]

[2]

4
[3]

int list[]
list[]={1,2,3,4};
{1,2,3,4};
printf(%x,%x,%d,list,&list[0],*list);

Output: ffe2de0c ffe2de0c 1


Output:ffe2de0cffe2de0c

CSE251Dr.CharlesB.Owen
ProgramminginC

PointersandArrays

p
list

int *p,
[[0]]
int list[]={1,2,3,4};
list[] {1 2 3 4};
p=list;
/*equivalenttop=&list[0]*/
printf(%d\n,*p);/*printsthevalue1*/

[[1]]

[[2]]

[[3]]

Youcanusea
pointertoaccess
thearray

CSE251Dr.CharlesB.Owen
ProgramminginC

Pointerand[]

Anypointertoablockofmemory
canusethe[]syntax,evenifitis
not declared as an array! List
notdeclaredasanarray!

[0]

[1]

[2]

[3]

int *p,
p
int list[]={1,2,3,4}; int *v;andint v[];/*Meanthesamething*/
p=list;
printf(%d\n,p[2]);
i tf(%d\ [2]) //prints3
// i t 3

CSE251Dr.CharlesB.Owen
ProgramminginC

*list Contentspointedtobylist
*(list+2) Contentsatlist[2]

Arrayindexing[]
list

list+2

ff 2d 0
ffe2de0c

ff 2d 10 ffe2de14
ffe2de10
ff 2d 14 ffe2de18
ff 2d 18

[0]

[1]

[2]

Indexinganarrayisjustaway
offindingaparticularaddress
inthatblock

[3]

int list[]
list[]={1,2,3,4}
= {1 2 3 4}
// array of 4 ints
//arrayof4ints
printf(%d,list[2]);
Thisisequivalentto
printf( %d , (list+2));
printf(%d,*(list+2));

10

CSE251Dr.CharlesB.Owen
ProgramminginC

PointerArithmetic
Whenweaddtoapointer,suchas(p+1),wedont
literallyadd1tothepointeraddress
Insteadweaddoneaddresstothepointer

11

CSE251Dr.CharlesB.Owen
ProgramminginC

PointerArithmetic
int list[]={1,2,3,4};
int *p=list;
/*sameasp=&list[0]*/
printf(%x,p);
printf(
%x ,p);/
/*printsffe2de0c
prints ffe2de0c */
/
p
ffe2de0c

12

ffe2de10 ffe2de14 ffe2de18

CSE251Dr.CharlesB.Owen
ProgramminginC

PointerArithmetic
int list[]={1,2,3,4};
int *p=list;
/*sameasp=&list[0]*/
printf(%x,p);
printf(
%x ,p);/
/*printsffe2de0c
prints ffe2de0c */
/
p=p+1;
/*pincreasesby4*/
printf(%x,p);/*printsffe2de10*/
Thinkofpointer
arithmeticasadd
1location
insteadofone
byte or address
byteoraddress.

13

p
ffe2de0c

ffe2de10 ffe2de14 ffe2de18

CSE251Dr.CharlesB.Owen
ProgramminginC

PointerArithmetic
doublelist2[]={1.0,2.0,3.0};
d
bl li t2[]
{1 0 2 0 3 0}
double*p=list2;/*sameasp=&list2[0]*/
printf(%x,p);/*printsffe2de0c*/
p
(
p)
p
p
ffe2de0c

ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20

1.0

14

2.0

3.0

CSE251Dr.CharlesB.Owen
ProgramminginC

PointerArithmetic
doublelist2[]={1.0,2.0,3.0};
d
bl li t2[]
{1 0 2 0 3 0}
double*p=list2;/*sameasp=&list2[0]*/
p
printf(%x,p);/*printsffe2de0c*/
(
p)
p
p=p+1;/*Pincreasesby8bytes*/
printf(%x,p);/*printsffe2de14*/
P

ffe2de0c

ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20

1.0

15

2.0

3.0

CSE251Dr.CharlesB.Owen
ProgramminginC

PointerArithmeticonArrays
*(list+1)referencesthenextelementinthearray
*(l
) f
h
l
h
(equivalenttolist[1])
Becareful:*(++list)workstoobutnowwehavelost
our pointer to the beginning of the array!!!
ourpointertothebeginningofthearray!!!
Equivalentto: list=list+1;*list;

16

CSE251Dr.CharlesB.Owen
ProgramminginC

sizeof()operator
iintt i;i
int *ptr4i=&i;
int IntArray[]={1,2,3,4,5};
double j;
doublej;
double*ptr4j=&j;
doubledoubleArray[]={1.0,2.0,3.0,4.0,5.0};

Returnsthenumber
of bytes needed to
ofbytesneededto
storeavariableora
data type
datatype

printf("Sizeof
i tf("Si f integeris%dbytes\n",sizeof(int));
i t
i %d b t \ " i f(i t))
printf("Sizeof doubleis%dbytes\n",sizeof(double));
printf("Sizeof i is%dbytes\n",sizeof(i));
printf("Sizeof pointerfori is%dbytes\n",sizeof(ptr4i));
printf("Sizeof jis%dbytes\n",sizeof(j));
printf("Sizeof pointerforjis%dbytes\n",sizeof(ptr4j));
printf("Sizeof intArray is%dbytes\n",sizeof(intArray));
printf("Sizeof doubleArray is%dbytes\n",sizeof(doubleArray));

17

CSE251Dr.CharlesB.Owen
ProgramminginC

sizeof()operator

18

CSE251Dr.CharlesB.Owen
ProgramminginC

Whenwepassanarray
Wh
Whenwepassanarray,wearepassingthearray
i th
address
int sumArray(int
sumArray( int [],int);
[ ] int);
int main()
{
int list[]={1,2,3,4);

sumArray(list
A
( li ,4);
4)

19

CSE251Dr.CharlesB.Owen
ProgramminginC

Whenwepassanarray
Thiswillworktoo(becausearraynameisapointerto
thebeginningofthearray)
int sumArray(int *, int);
int main()
{
int list[]={1,2,3,4);

sumArray(list ,4);

20

CSE251Dr.CharlesB.Owen
ProgramminginC

Whenwepassanarray
ButthisDOESNOT work!
int sumArray(int
y(
*,int);
, );
int main()
{
int *list={1,2,3,4);
*list {1 2 3 4);

sumArray(list,4);

21

CSE251Dr.CharlesB.Owen
ProgramminginC

*list Contentspointedtobylist
*(list+2) Contentsatlist[2]

Pointers
list
ff 2d 0
ffe2de0c

list+2
ff 2d 10 ffe2de14
ffe2de10
ff 2d 14 ffe2de18
ff 2d 18

[0]

[1]

[2]

Indexinganarrayisjusta
wayoffindingaparticular
addressinthatblock

[3]

int list[]
list[]={1,2,3,4}
= {1 2 3 4}
// array of 4 ints
//arrayof4ints
printf(%d,list[2]);
Thisisequivalentto
printf( %d , (list+2));
printf(%d,*(list+2));

22

CSE251Dr.CharlesB.Owen
ProgramminginC

2DArrays
int cave[ArraySize][ArraySize];
Column
0
1

Row

2
3

23

1
5
9
13

2
6
10
14

3
7
11
15

4
8
12
16

CSE251Dr.CharlesB.Owen
ProgramminginC

2DArrays
int myMatrix[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
myMatrix[3][4] = { {1 2 3 4} {5 6 7 8} {9 10 11 12} };
Column
0

Row

1
2

1
5
9

2
6
10

3
7
11

4
8
12

myMatrix[0][1] 2

myMatrix[2][3]
M t i [2][3] 12
myMatrix[row][col]

24

CSE251Dr.CharlesB.Owen
ProgramminginC

Physically,inoneblockofmemory
int myMatrix[2][4]={{1,2,3,4},{5,6,7,8}};
ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28

2
row1

row2

Arrayelementsarestoredinrowmajororder
Array
elements are stored in row major order
Row1first,followedbyrow2,row3,andsoon

25

CSE251Dr.CharlesB.Owen
ProgramminginC

2DArrayNameandAddresses
int myMatrix[2][4]={{1,2,3,4},{5,6,7,8}};
[ ][ ] { {
}{
}}
ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28

myMatrix:pointertothefirstelementofthe2Darray
myMatrix[0]:pointertothefirstrowofthe2Darray
myMatrix[1]:pointertothesecondrowofthe2Darray
*myMatrix[1]istheaddressofelementmyMatrix[1][0]

26

CSE251Dr.CharlesB.Owen
ProgramminginC

Accessing2DArrayElements
int myMatrix[2][4]={{1,2,3,4},{5,6,7,8}};
[ ][ ] { {
} {
}}
1

Indexing:myMatrix[i][j]issameas
g y
[ ][j]
*(myMatrix[i]+j)
(*(myMatrix +i))[j]
*((*(myMatrix +i))+j)
+ i)) + j)
*(&myMatrix[0][0]+4*i +j)

27

CSE251Dr.CharlesB.Owen
ProgramminginC

Declaration
#defineROWS3
#defineCOLS5
int table[ROWS][COLS];
voiddisplay(table);

28

CSE251Dr.CharlesB.Owen
ProgramminginC

voiddisplay(int x[ROWS][COLS])
2DArraysoftenrequire
{
nestedloops
p two
for(int i=0;i <ROWS;i++)
variables
{
( jj=0;j<COLS;j++)
;j
;j )
for(int
{
printf("x[%d][%d]:%d",i,j,x[i][j]);
}
printf("\n");
}
printf("\n");
}

29

CSE251Dr.CharlesB.Owen
ProgramminginC

TableA={{13,22,9,23},
{17,5,24,31,55},
{4 19 29 41 61} };
{4,19,29,41,61}};

TableB={1,2,3,4,
5,6,7,8,9,
10 11 12 13 14 };
10,11,12,13,14};

30

13
17
4

22
5
19

9
24
29

23
31
41

?
55
61

1
6
11

2
7
12

3
8
13

4
9
14

5
10
?

CSE251Dr.CharlesB.Owen
ProgramminginC

passing2darrays
Inpassingamultidimensionalarray,thefirstarraysize
doesnothavetobespecified.Thesecond(andany
subsequent)dimensionsmustbegiven!
int myFun(int list[][10]);

31

CSE251Dr.CharlesB.Owen
ProgramminginC

#defineROWS3
#defineCOLS5
int addMatrix(int
addMatrix( int [][COLS]);
[ ][COLS] );
int main()
{
int a[][COLS]={{13,22,9,23,12},{17,5,24,31,55},{4,19,29,41,61}};
a[][COLS] = { {13 22 9 23 12} {17 5 24 31 55} {4 19 29 41 61} };
printf(Sum=%d\n,addMatrix(a));
}
int addMatrix( int t[][COLS])
t[ ][COLS] )
{
int i,j,sum=0;
for (i=0; i<ROWS; i++)
for(i=0;i<ROWS;i++)
for(j=0;j<COLS;j++)
sum+=t[i][j];
returnsum;;
}

32

CSE251Dr.CharlesB.Owen
ProgramminginC