a short review arrays, pointers and structures. what is an array? an array is a collection of...
TRANSCRIPT
A Short Review Arrays, Pointers and Structures
What is an Array? An array is a collection of variables of the same type and placed in
memory contiguously .
The set of data of data in an array is only given one name and the indices are used to differentiate each of the data.
The array is important to avoid redundancy of variable declaration and for easy access of data that are placed contiguously in memory.
It is the job of the programmer to ensure that the array is large enough to hold what the program will put in them.
One Dimensional Array
Syntax Declaration:
<base_type> var_name[size]; <base_type> var_name[size] = {optional initialization
data};
Total Size of the Array in bytes:
total bytes = sizeof(base type) * number of elements
a[0]
a[1]
a[2]
a[3]
a[4]
a[5]
a[6]
One Dimensional ArrayExample: int num[5]= { 2, 4, 3, 10, 20};
20
2 4 3 10
Index 0 1 2 3 4
Data num[0] num[1] num[2] …
Address &num[0] &num[1] &num[2] …
or num
Note: Min Index =0
Max Index = size -1
Important:
The name of the array is the starting address of the array.
One Dimensional ArraySample Program : Compute Sum of Array Inputs
1 /* Filename: SumArray.c
Program Description: Ask 5 integers and compute the sum.
Programmer: Pedro de la Cruz
Date Written: May 29,2005
*/ Sample Output:
Enter a number: 3
Enter a number: 1
Enter a number: 2
Enter a number: 5
Enter a number: 2
Sum = 13
2
3
4
5
6
7
8
9
10
#include<stdio.h>
int main(void)
{ int num[5];
int x, sum=0;
for(x=0; x<5; x++)
{ printf(“Enter a number: “);
scanf(“%d”, &num[x]);
}
for(x=0; x<5; x++)
sum += num[x];
printf(“\nSum=%d”, sum);
}
11
12
13
14
15
16
FF04
func1(int *a) /*pointer */{ . . . }
Passing One Dimensional Arrays
FF00 FF02. . . . .
main(void){ int a[7];
func1(a); . . . }
func1(int a[7]) /*sized array */{ . . . }
func1(int a[ ]) /*unsized array */{ . . . }
7
Syntax Declaration:
<data_type> array_name[row][column] = {optional initialization data};
Example: int num[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 1, 0};
Note:
Min Col & Row =0
Max Row = Row – 1
Max Col = Column – 1
Size of array = col x row x size of data
Important:
When the name of the array is used with only 1 index specifying the row, it refers to the address of the first element of the row.
1 2 3 4
Column
0 1 2 3
5 6 7 8
9 3 1 0
0
1
2
Row
Data = num[0][0]
Address = &num[0][0]
or num[0]
Two Dimensional Array
8
Sample Program : Fill a Two-dimensional Array
1 /* Filename: Function1.c
Program Description: Ask 6 integers and place it in a 2x3 array.
Programmer: Pedro de la Cruz
Date Written: May 29,2005
*/
Sample Output:
Enter a number: 1
Enter a number: 10
Enter a number: 2
Enter a number: 20
Enter a number: 3
Enter a number: 30
2
3
4
5
6
7
8
9
10
#include<stdio.h>
int main(void)
{ int x[2][3];
int row, col;
for(row=0; row<3; row++)
{
for(col=0; col<2; col++)
{ printf(“Enter a number: “);
scanf(“%d”, &num[row][col]);
}
}
}
11
12
13
14
15
16
17
18
19
Two Dimensional Array
9
Multidimensional arrays can have three, four or more dimensions.
Example: 3-Dimensional Array
4 5 6 7
3 4 5 6
1 2 3 4
5 6 7 8
0 1 2 30
1
23
4
0 1 2 30
12
Row
Column
Plane
Syntax:
<data_type> array_name[plane][row][column]
int table[3][5][4] =
{ { /*Plane 0*/
{0,1,2,3}, /*Row 0*/
{1,2,3,4}, /*Row 1*/
{3,4,5,6}, /*Row 2*/
{4,5,6,7}, /*Row 3*/
{5,6,7,8}, /*Row 4*/
}
}
Multi-Dimensional Array
10
Multi-Dimensional Array
Sample Program : Multidimensional Array
1 /* Filename: MultiDim.c
Program Description: Multidimensional Array sample
Programmer: Pedro de la Cruz
Date Written: May 29,2005
*/
Output:
0 1 2 3
1 2 3 4
2 3 4 5
2
3
4
5
6
7
8
9
10
#include<stdio.h>
main()
{ int table[3][3][4]=
{
{ /*Plane 0*/
{0,1,2,3},
{1,2,3,4},
{2,3,4,5},
}
};
int plane, row, col;
for(plane=0;plane<1; plane++)
{
for(row=0; row<3; row++)
{
for(col=0; col<4; col++)
printf(“\t%d”, table[plane][row][col]);
printf(“\n”);
}
}
}
11
12
13
14
15
16
17
18
19
Arrays and PointersClosely related in C
char p [10];p = = &p[0] TRUE
Example: one – dimensional arraysint *p, i [10];p = i;p [5] = 100; /* assign using index */
*(p + 5) = 100;/*assign using pointer arithmetic */
Arrays and PointersExample: two dimensional arrays assuming
that a is a 10 by 10 array
a = = &a [0] [0]
a [j] [k] is equivalent to *((*a) + (j row length) + k)
Allocated ArraysIn C, you can dynamically allocate and free
memory by using the standard library routines malloc( ), which allocates memory and returns a void * pointer to the start of it, and free( ) which returns previously allocated memory to the heap for possible reuse.
Example:
/* allocating 1000 bytes of memory */
char *p;
p = malloc(1000);
/* Print a string backwards using dynamic allocation. */
# include <stdlib.h># include <stdio.h># include <string.h>
int main (void){
char *s;int t;
s = malloc (80);
if (!s) { printf (“memory request failed\n”) ; return 1;
}gets (s);for (t= strlen (s) – 1; t > = 0; t - - ) printf ( “%c”, s [t] );free (s);return 0;
}
SeatworkCreate a program that will save the
following data in
1 2 3 4 51 1 1 1 12 4 8 16 323 9 27 81 243···
What is a Pointer?A pointer is a special type of variable that
contains a memory address which could be used to access data
Data Variableint x=5;
Pointer Variable
p=FF00
x=5&x
data
address
x = data inside address &x
&x = address
p = address
*p = the data inside address p
int *p;
p=&x;
x=5&x =FF00
What is a Pointer?1. A pointer provides the means with which
functions can modify their calling arguments.
2. A pointer is used to support Turbo C’s dynamic allocation system.
3. The use of pointers can improve the efficiency of certain routines
4. A pointer is commonly used to support certain data structures such as linked lists and binary trees.
Pointer VariablesA pointer declaration consists of a base type,
an *, and the variable name.
Syntax Declaration:
<data_type> *var_name;
Defines what type of variables the pointer can point to.
Pointer OperatorsTwo special pointer operators:
*&
& is a unary operator that returns the memory address of its operand
* is the complement of &; a unary operator that returns the value of the variable located at the address that follows
Pointer ExpressionsPointer assignments
As with any variable, a pointer may be used on the right-hand side of assignment statements to assign its value to another pointer
Pointer arithmeticArithmetic operations are performed to the
pointer relative to its base type Addition and subtraction of a pointer and an integer Subtraction of a pointer from another pointer (only
when it makes sense)
Pointer ExpressionsPointer comparisons
It is possible to compare two pointers in a relational expression
Generally used when two or more pointers are pointing to a common object
Dynamic Allocation FunctionsUpon compilation
Program codeGlobal dataStackHeap
An area of free memory managed by C’s dynamic allocation functions
Dynamic Allocation FunctionsThis code fragment allocates 25 bytes of
memorychar *p;
p = malloc(25);
No type cast is used because the pointer type is converted automatically to the same type as the pointer variable
Dynamic Allocation FunctionsAnother example: int *p; p = malloc(50*sizeof(int));
It is imperative to check the value returned by malloc( ) to make sure that it is not null before using the pointer.
if((p=malloc(100))==NULL) { printf(“Out of memory. \n”); exit(1); }
Find the error in this program#include<stdio.h>
#include<string.h>
main(void)
{
char *p1, s[80];
p1 = s;
do {
gets(s);
while (*p1) printf(“%d”, *p1++);
} while (strcmp(s, “done”));
return 0;
}
}
Pointers to PointersA pointer to a pointer is a form of multiple
indirection, or a chain of pointers
Single Indirection
valueaddress
Pointer Variable
Multiple Indirection
address address value
Pointer Pointer Variable
Pointers to PointersA variable that is a pointer to a pointer must
be declared as such float **newbalance;
In order to acess the target value indirectly pointed to by a pointer to a pointer, the asterisk operator must be applied twice as shown:
printf(“ %f ”,**newbalance);
Initializing PointersBy convention, a pointer that is pointing to
nowhere should be given the value null to signify that is points to nothing
Pointers to FunctionsEven though a function is not a variable, it
still has a physical location in memory that can be assigned to a pointer
Read on how the address of a function is obtained
Read on how to create an array of function pointers for user-defined functions
Problems with Pointersmain(void)
{
int x, *p;
x=10;
*p = x;
return 0;
}
main(void)
{
int x, *p;
x = 10;
p = x;
printf(“%d”, *p);
return 0;
}
Seatwork Predict the output:
int main(void){ int num[5] = {10,20,30,40,50}; int *p1, *p2;
p1= num; p2 = p1; *p1 = *p1++ + *p2 + 5; *p2 = *(p1+2) + 10;
printf(“\n%d”, *p1); printf(“\n%d”, *p2);
return 0;}
StructuresThe C language gives you five ways to create
custom data types. One of these is through the creation of structures.
What is a Structure?The structure is a collection of variables
referenced under one name, providing a convenient means of keeping related information together.
Structuresstruct addr { char name[30];
char street[40];char city[20];char state[3];unsigned long int zip;
};
Structure Declaration
Structure Elements
Tells the compiler that a structure is being declared
Ends with a semicolon because it is a statement
Structure name or tag or type specifier
StructuresTo declare an actual variable with this
structurestruct addr addr_info;
name
street
city
state
zip
addr_info
Structuresstruct addr { char name[30];
char street[40];char city[20];char state[3];unsigned long int zip;
} addr_info, binfo, cinfo;
Declaration of variables with structure declaration
StructuresIf you need only one structure, no structure
name is neededstruct { char name[30];
char street[40];char city[20];char state[3];unsigned long int zip;
} addr_info;
Referencing Structure ElementsIndividual structure elements are referenced
by using the . (dot operator)Example:
addr_info.zip = 12345;
printf(“%ld”, addr_info.zip);gets(addr_info.name);
Arrays of Structuresstruct addr addr_info[100];
printf(“%ld”, addr_info[2].zip);
Passing Structures to FunctionsPassing Structure Elements to Functionsstruct fred {
char x;int y;float z;char s[10];
} mike;
func1(mike.x);func2(mike.y);func(mike.s[2]);
func1(&mike.x);func2(&mike.y);func(&mike.s[2]);
func(mike);
void func(struct fred parm){
}
Structure Pointersstruct bal {
float balance;char name[80];
} person;
struct bal *p;p = &person;p->balance;