0% found this document useful (0 votes)
2 views

Array

The document provides an overview of arrays and pointers in C programming, detailing their definitions, types, indexing, initialization, and memory management. It explains both single and multi-dimensional arrays, as well as the importance of pointers and their relationship with arrays. Additionally, it highlights common mistakes and cautions regarding array bounds and pointer arithmetic.

Uploaded by

Indah Pakpahan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Array

The document provides an overview of arrays and pointers in C programming, detailing their definitions, types, indexing, initialization, and memory management. It explains both single and multi-dimensional arrays, as well as the importance of pointers and their relationship with arrays. Additionally, it highlights common mistakes and cautions regarding array bounds and pointer arithmetic.

Uploaded by

Indah Pakpahan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Basic Programming

Arrays and Pointers

Prepared by: Inte Christinawati Bu'ulolo


Present and Edited by: Gerry Wowiling
Topics
 Array Definition
 Array Indexing
 Arrays in C
 Single Dimension Array (static)
 Multi Dimension Array (static)
 Array Initialization
 Single Dimension Array (dynamic)
 Multi Dimension Array (dynamic)
 Size of array
 Introduction to pointer

ICB/DASPRO 2
Definition – Array
• A collection of objects of the same type
stored contiguously in memory under one
name
• May be type of any kind of variable
• May even be collection of arrays!

• An array is variable that can store multiple


values (one type)
• For ease of access to any member of array
• For passing to functions as a group
ICB/DASPRO 3
Array Indexing
• Definition:– Array Index – the expression between the square brackets
• Also called an Array Subscript
• In C, all arrays consist of contiguous memory locations.
• An element in an array is accessed by an index.
• Index array always started from 0 to array size - 1
• The lowest address (0) corresponds to the first element and the highest (array
size -1) address to the last element.
• Arrays can have from one to several dimensions.

ICB/DASPRO 4
Arrays in C
• datatype arrayName[arraySize]
• int a[10]
• An array of ten integers
• a[0], A[1], …, A[9]
• double b[20]
• An array of twenty long floating point numbers
• b[0], b[1], …, b[19]
• int c[]
• An array of an unknown number of integers (allowable in a parameter of a
function)
• C[0], C[1], …, C[max-1]
• int d[10][20]
• An array of ten rows, each of which is an array of twenty integers
• D[0][0], D[0][1], …, D[1][0], D[1][1], …, D[9][19]
• Not used so often as arrays of pointers
• Arrays of structs, unions, pointers, etc., are also
allowed
ICB/DASPRO 5
Single Dimension Array
• Declaring single dimension array:
dataType arrayName [arraySize ];
• Example:
int a[10];

• Setting element by array index:


a [0] = 100;

• Accessing element by array index:


printf(“%d”, a [0]);

ICB/DASPRO 6
Single dimensional array: example

ICB/DASPRO 7
Multidimensional Array
• A multidimensional array has more than one
subscript.
• Two-dimensional array has two subscripts, a
three dimensional array has three subscripts,
and so on.
• There is no limit to the number of dimensions
a C array can have.
• Example:
int a[10][2] /*[row][col]*/
A one-dimensional array with 10 elements, each of
which is an array with 2 elements
ICB/DASPRO 8
Multidimensional
Array: example

ICB/DASPRO 9
Array Initialization
• Array declaration by initializing elements
int arr[] = {10, 20, 30, 40}
• Compiler creates an array of size 4.
• above is same as "int arr[4] = {10, 20, 30, 40}"
• Array declaration by specifying size and initializing elements
int arr[6] = {10, 20, 30, 40}
• Compiler creates an array of size 6, initializes first
• 4 elements as specified by user and rest two elements as 0.
• above is same as "int arr[] = {10, 20, 30, 40, 0, 0}“
• int C[4] = {2, 4, 8, 16, 32};
• Error — compiler detects too many initial values
ICB/DASPRO 10
Initializing a Two-Dimensional Array
char daytab[2][12] = {
{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}
}; // daytab

OR

char daytab[2][12] = {
31,28,31,30,31,30,31,31,30,31,30,31,
31,29,31,30,31,30,31,31,30,31,30,31
}; // daytab
ICB/DASPRO 11
Caution! Caution! Caution!
• It is the programmer’s responsibility to avoid indexing off the end of
an array
• Likely to corrupt data
• May cause a segmentation fault
• Could expose system to a security hole!
• C does NOT check array bounds
• I.e., whether index points to an element within the array
• Might be high (beyond the end) or negative (before the array starts)

ICB/DASPRO 12
Caution! Caution! Caution!
• It is the programmer’s responsibility to avoid indexing off the end of
an array
• Likely to corrupt data
• May cause a segmentation fault
• Could expose system to a security hole!
• C does NOT check array bounds
• I.e., whether index points to an element within the array
• Might be high (beyond the end) or negative (before the array starts)

ICB/DASPRO 13
Questions
Declaring Arrays: static vs dynamic
• Declaration
• Allocation
• Initialization
• Deallocation

ICB/DASPRO 15
Single dimensional array (dynamic):
example

ICB/DASPRO 16
Multidimensional
Array (dynamic):
example

ICB/DASPRO 17
Getting Size of Implicit Array
• sizeof operator – returns # of bytes of memory
required by operand
• See p.135 of K&R, §7.7 of D&D
• Examples:–
• sizeof (int) – # of bytes per int
• sizeof (float) – # of bytes per float
• sizeof a – # of bytes in array a (previous slide)
• # of elements in days = (sizeof a)/sizeof(int)

• Must be able to be determined at compile time


• Getting size of dynamically allocated arrays not supported

ICB/DASPRO 18
Getting Size of Implicit Array
• sizeof operator – returns # of bytes of memory
e s e s
required by operand p a r e nth
• See p.135 w i th pe
ty
i z e o o f th e
f
s ze s es
• Examples:– is s i
o p a ren t h e
je ct
n
f –int of the o b
• sizeof (int) – # of bytes e per
o
si z
n s s ize
• sizeof (float) – # of bytesmea per float
• sizeof a – # of bytes in array a (previous slide)
• # of elements in days = (sizeof a)/sizeof(int)

• Must be able to be determined at compile time


• Getting size of dynamically allocated arrays not supported

ICB/DASPRO 19
Questions?
Definition – Pointer
11 ∙∙∙
0 1 2 3 4 5 6 7 8 9 10 11 2n-1

• A value indicating the number of a data object


• Also called an Address or a Location
• Special variables that are used to store address rather
than values
• Used in machine language to identify which data to
access
• E.g., stack pointer is address of most recent entry of The Stack
• Usually 2, 4, or 8 bytes, depending upon machine
architecture
ICB/DASPRO 21
Pointers in C
'&'
• Used everywhere ry
in a D )
a s b N
m e s e A
• For building useful,
h e sa interesting,
it w i data structures
t b
r ( functions
Not data
• For returning r at ofrom
o pe
• For managing arrays
• '&' unary operator generates a pointer to x
• E.g., scanf("%d", &x);
• E.g., p = &c;
• Operand of '&' must be an l-value — i.e., a legal object on left of assignment operator ('=')
• & is used to access the address
• Unary '*' operator dereferences a pointer
• i.e., gets value pointed to
• E.g. *p refers to value of c (above)
• E.g., *p = x + y; *p = *q;

ICB/DASPRO 22
Declaring Pointers in C
• int *p; — a pointer to an int
• double *q; — a pointer to a double
• char **r; — a pointer to a pointer to a
char
• int *pc, p1; — a pointer of pc and normal variable of p1
• type *s; — a pointer to an object of
type type
• E.g, a struct, union, function, something defined by a typedef, etc.

ICB/DASPRO 23
Pointers in C

5 is assigned to the c variable, and the


address of c is assigned to the pc pointer

The address of c is assigned to pc pointer. To


get the values stored in c address we used *pc

printf(“%d”, pc) -> output = ?


printf(“%d”, *pc) -> output = ?

ICB/DASPRO 24
Common Mistakes

The above code will not error!

Equivalent to:
int* pc

*pc

ICB/DASPRO 25
Pointer Arithmetic
• int *p, *q;
q = p + 1;
• Construct a pointer to the next integer after *p and assign it to
q
• double *p, *r;
int n;
r = p + n;
• Construct a pointer to a double that is n doubles beyond *p,
and assign it to r
• n may be negative

ICB/DASPRO 26
Pointer Arithmetic (continued)

• long int *p, *q;


p++; q--;
• Increment p to point to the next long int; decrement q to point to the
previous long int
• float *p, *q;
int n;
n = p – q;
• n is the number of floats between *p and *q; i.e., what would be added to q
to get p

ICB/DASPRO 27
Pointer Arithmetic (continued)
c k s th a t the id
is v al
e r che ointer
ev p
C n ulting
res
• long int *p, *q;
p++; q--;
• Increment p to point to the next long int; decrement q to point to the
previous long int
• float *p, *q;
int n;
n = p – q;
• n is the number of floats between *p and *q; i.e., what would be added to q
to get p

ICB/DASPRO 28
Why introduce pointers in the middle of a lesson
on arrays?
• Arrays and pointers are closely related in C
• In fact, they are essentially the same thing!
• Esp. when used as parameters of functions
• int A[10];
int *p;
• Type of A is int *
• p = A; and A = p; are legal assignments
• *p refers to A[0]
*(p + n) refers to A[n]
• p = &A[5]; is the same as p = A + 5;
ICB/DASPRO 29
Arrays and Pointers (continued)

• double A[10]; vs. double *A;


• Only difference:–
• double A[10] sets aside ten units of memory, each large enough to hold a
double, and A is initialized to point to the zeroth unit.
• double *A sets aside one pointer-sized unit of memory, not initialized
• You are expected to come up with the memory elsewhere!
• Note:– all pointer variables are the same size in any given machine
architecture
• Regardless of what types they point to

ICB/DASPRO 30
Note
• C does not assign arrays to each other
• E.g,
• double A[10];
double B[10];

A = B;
• assigns the pointer value B to the pointer value A
• Original contents of array A are untouched (and possibly unreachable!)

ICB/DASPRO 31
Questions?

You might also like