410 likes | 518 Views
C Programming. 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 .
E N D
C Programming 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]
2 4 3 10 20 Data num[0] num[1] num[2] … Address&num[0] &num[1] &num[2] … or num One Dimensional Array • Example: int num[5]= { 2, 4, 3, 10, 20}; Index 0 1 2 3 4 Note:Min Index =0 Max Index = size -1 Important: The name of the array is the starting address of the array.
Passing One Dimensional Arrays • Example: func1(int *a) /*pointer */ { . . . } a[0] a[1] a[2] a[3] a[4] a[5] a[6] . . . . . func1(int a[ ]) /*unsized array */ { . . . } FF02 FF00 FF04 main(void) { int a[7]; func1(a); . . . } func1(int a[7]) /*sized array */ { . . . }
Column 0 1 2 3 1 5 9 6 2 3 3 1 7 4 0 8 0 Row 1 2 Two Dimensional Array • 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. Data = num[0][0] Address = &num[0][0] or num[0]
0 1 2 4 3 1 0 5 6 2 4 5 1 2 7 6 3 5 4 7 6 8 3 3 2 4 1 0 0 1 2 3 Multi-Dimensional Array • Multidimensional arrays can have three, four or more dimensions. • Example: 3-Dimensional Array 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*/ } } Row Plane Column
Arrays and Pointers • Closely related in C char p [10]; p = = &p[0] TRUE Example: one – dimensional arrays int *p, i [10]; p = i; p [5] = 100; /* assign using index */ *(p + 5) = 100;/*assign using pointer arithmetic */
Arrays and Pointers • Example: 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 Arrays • In 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; }
Seatwork • Create a program that will save the following data in 1 2 3 4 5 1 1 1 1 1 2 4 8 16 32 3 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 &x =FF00 x=5 int *p; p=&x; &x x=5 address p=FF00 data p = address *p = the data inside address p x = data inside address &x &x = address
What is a Pointer? • A pointer provides the means with which functions can modify their calling arguments. • A pointer is used to support Turbo C’s dynamic allocation system. • The use of pointers can improve the efficiency of certain routines • A pointer is commonly used to support certain data structures such as linked lists and binary trees.
Pointer Variables • A 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 Operators • Two 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 Expressions • Pointer 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 arithmetic • Arithmetic 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 Expressions • Pointer 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 Functions • Upon compilation • Program code • Global data • Stack • Heap An area of free memory managed by C’s dynamic allocation functions
Dynamic Allocation Functions • This code fragment allocates 25 bytes of memory char *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 Functions • Another 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 Pointers Pointer Variable address value Single Indirection Pointer Variable Pointer address address value Multiple Indirection • A pointer to a pointer is a form of multiple indirection, or a chain of pointers
Pointers to Pointers • A 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 Pointers • By convention, a pointer that is pointing to nowhere should be given the value null to signify that is points to nothing
Pointers to Functions • Even 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 Pointers main(void) { int x, *p; x = 10; p = x; printf(“%d”, *p); return 0; } main(void) { int x, *p; x=10; *p = x; 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; }
Structures • The 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.
Structures Structure name or tag or type specifier Structure Elements struct addr { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; }; Structure Declaration Tells the compiler that a structure is being declared Ends with a semicolon because it is a statement
Structures • To declare an actual variable with this structure struct addr addr_info; name 30 bytes street 40 bytes city 20 bytes addr_info state 3 bytes zip 4 bytes
Structures struct 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
Structures • If you need only one structure, no structure name is needed struct { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; } addr_info;
Referencing Structure Elements • Individual 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 Structures struct addr addr_info[100]; printf(“%ld”, addr_info[2].zip);
Passing Structures to Functions • Passing Structure Elements to Functions struct fred { char x; int y; float z; char s[10]; } mike; func1(mike.x); func2(mike.y); func(mike.s[2]); func(mike); func1(&mike.x); func2(&mike.y); func(&mike.s[2]); void func(struct fred parm) { }
Structure Pointers struct bal { float balance; char name[80]; } person; struct bal *p; p = &person; p->balance;