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: var_name[size]; 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 Array Example: int num[5]= { 2, 4, 3, 10, 20}; Index 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 Array Sample 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 = #include 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); }
FF04 func1(int *a) /*pointer */ {. } Passing One Dimensional Arrays Example: a[0]a[1]a[2]a[3]a[4]a[5]a[6] FF00FF main(void) { int a[7]; func1(a);. } func1(int a[7]) /*sized array */ {. } func1(int a[ ]) /*unsized array */ {. }
7 Syntax Declaration: 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 Column 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: #include 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]); } Two Dimensional Array
9 Multidimensional arrays can have three, four or more dimensions. Example: 3-Dimensional Array Row Column Plane Syntax: 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: #include 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); }
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 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 ·
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 Variable int 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 Cs 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 Variables A pointer declaration consists of a base type, an *, and the variable name. Syntax Declaration: *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 Cs 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 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 A pointer to a pointer is a form of multiple indirection, or a chain of pointers Single Indirection value address PointerVariable Multiple Indirection address value Pointer Variable
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; 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; }
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 struct 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
Structures To declare an actual variable with this structure struct addr addr_info; 30 bytes 40 bytes 20 bytes 3 bytes 4 bytes name street city state zip addr_info
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]); func1(&mike.x); func2(&mike.y); func(&mike.s[2]); func(mike); void func(struct fred parm) { }
Structure Pointers struct bal { float balance; char name[80]; } person; struct bal *p; p = &person; p->balance;