380 likes | 509 Views
5. Arrays, Strings, Pointers. Adapted from: http://students.iitk.ac.in/programmingclub/course/#notes Practical C Programming Textbook. Arrays. An Array is a collection of variables of the same type that are referred to through a common name. Declaration type var_name[size] e.g .
E N D
5. Arrays, Strings, Pointers Adapted from: http://students.iitk.ac.in/programmingclub/course/#notes Practical C Programming Textbook
Arrays • An Array is a collection of variables of the same type that are referred to through a common name. • Declaration type var_name[size] e.g int marks[10]; double weights[15];
Array Initialization After declaration, array contains some garbage value. Static initialization Run time initialization int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int i; int A[6]; for(i = 0; i < 6; i++) { printf(“enter %d th element\n”, i); scanf(“%d”, &A[i]); } int i; int A[6]; for(i = 0; i < 6; i++) A[i] = 6 - i;
Memory addresses • Memory is divided up into one byte pieces individually addressed. - minimum data you can request from the memory is 1 byte • Each byte has an address. for a 32 bit processor, addressable memory is 232 bytes. To uniquely identify each of the accessible byte you need log2232 = 32 bits
Array - Accessing an element int A[6]; 6 elements of 4 bytes each,total size = 6 x 4 bytes = 24 bytes Read an element Write to an element // int tmp = A[2]; A[3] = 5;
Arrays As Function Args main(){ int B[3]={1,2,3}; funcName(B); } funcName(int A[]) { } funcName(int *A) { } funcName(int A[10]) { } C Course, Programming club, Fall 2008
int main() { int marks[140]; int i; printf("\n"); for ( i = 0; i < 140; i++) { printf(“enter marks[%d] \n",i); scanf(“%d", &marks[i]); } int sum = 0; for ( i = 0; i < 140; i++) { sum += marks[i]; } double average = sum / 140.0; printf("\nThe average of the marks is %.2f\n", average); return 0; }
Strings in C • No “Strings” keyword • A string is an array of characters. OR char string[] = “hello world”; char *string = “hello world”;
Significance of NULL character ‘\0’ • Compiler has to know where the string ends • ‘\0’ denotes the end of string ‘\n’ = new line, ‘\t’ = horizontal tab, ‘\v’ = vertical tab, ‘\r’ = carriage return‘A’ = 0x41, ‘a’ = 0x61, ‘\0’ = 0x00 char string[] = “hello world”; printf(“%s”, string);
Different ways to initialize Strings char a[5] = { 'h', 'e', 'l', 'l', 'o'}; /* No '\0' at the end, will print some garbage values too */ char a[6] = { 'h', 'e', 'l', 'l', 'o', '\0'}; /* Putting a '\0' at the end, prints string correctly */ char a[] = "hello"; /* This is the most common way to declare a string */ char *a = "hello"; /* Use of a char pointer */
Strings • Length of string can be different from size of string array • char name[50]=“MOHAN”; • char name[]=“MOHAN”; • Size of array, string? • String constants • String and character constants are different • Char ch=‘L’; • Char str[]=“L”;
String Manipulation • <string.h> contains std functions for string manipulation • Reading strings, <stdio.h> • fgets(name, sizeof(name),stdin);
Example: Full Name C Course, Programming club, Fall 2008
float avgMarks(int scores[140], int scores); int main() { int marks[140]; int i; printf("\n"); for ( i = 0; i < 140; i++) { printf(“enter marks[%d] \n",i); scanf(“%d", &marks[i]); } printf("\nThe average of the marks is %.2f\n", avgMarks(&marks[0],140); return 0; } float avgMarks(int scores[140], int count) { //or (int scores[], int count) int i, sum = 0; for ( i = 0; i < count; i++) { sum += scores[i]; } return (sum / (float) count); } Passing Arrays to Functions C Course, Programming club, Fall 2008
Pointers in C x x 10 10 0x1000 0x1000 0x1000 20 0x1002 0x1002 0x1002 y int x=10; int x=10; int y=20; • &x returns the address of variable x • C uses new types to store addresses • int *ptr = &y; • ptr is a variable of type int * • In other words, variable ptr can hold an address of memory locations containing integer values • In other words, variable ptr is a pointer that points to memory locations containing integer values ptr 0x1002 0x2000
Analogy • Villa name is “VasanthBhavan” • “VasanthBhavan” is having 10 rooms • “VasanthBhavan” is located at coordinates <78.4, 67.7, 0.0> Villa Vasanth_Bhavan=10 rooms; Villa *address=<78.4, 67.7, 0.0> or Villa *address=&Vasanth_Bhavan;
Pointers in C • A char pointer points to a single byte. • An int pointer points to first of the four bytes. • A pointer itself has an address where it is stored in the memory. Pointers are usually four bytes. • * is called the dereference operator • *p gives the value pointed by p 4 i p • & (ampersand) is called the reference operator • &i returns the address of variable i int *p; int* p; int i = 4; p = &i;
More about pointers int x = 1, y = 2, a[10]; int *ip; /* A pointer to an int */ ip = &x; /* ip gets address of x */ y = *ip;/* y gets content of location pointed by ip */ *ip=y; /* location pointed by ip gets value of y */ *ip = 0; /* Clear location where ip points */ ip = &a[0]; /* Address of first element of array a */
#include <stdio.h> int main() { int x = 10; int *p; p = &x; printf("p = %p\n", p); /* What does p contain? */ printf("&x = %p\n", &x); /* What is the address of x? */ printf("*p = %d\n", *p); /* What value does p reference to? */ printf("&p = %p\n", &p); /* What is the address of p, btw? */ return 0; }
Pointer Arithmetic • A 32-bit system has 32-bit address space. • To store any address (int/float/double/long/char/array/struct), 32 bits are required. int *ptr; float *ptr; • Pointer arithmetic : ptr+1 gives the next memory location assuming cells are of the same type as the base type of ptr.
Allowed Operations on Pointers int *px, *py; int x, y; px = &x; /* get address */ py = &y; px = py; /* assignment; both */ /* lhs and rhs are same type */ px = NULL; /* assignment to NULL */ int n = px - py; /* should point to same array objects & returns no of objects */ if ( px == NULL) /* comparison */ printf("pointer is NULL\n");
NOT Allowed on Pointers int *px, *py, *pz; px = 12; /* assignment to */ /* non-NULL literal */ pz = px + py; /* add two pointer values*/ px = py * 2 /* multiply or divide */ /* of pointer value(s)*/
Pointer Arithmetic: Example int *p, x = 10; p = &x; printf("p = %p\n", p); printf("p+1 = %p\n", (int*)p+1); printf("p+1 = %p\n", (char*)p+1); printf("p+1 = %p\n", (float*)p+1); printf("p+1 = %p\n", (double*)p+1); Sample output: p = 0022FF70 p+1 = 0022FF74 p+1 = 0022FF71 p+1 = 0022FF74 p+1 = 0022FF78
C uses pointer notation with arrays: a[i] is equivalent to *(a + i) and &a[i] is equivalent to a + i
Pointers and arrays • Pointers and arrays are tightly coupled. char a[] = “Hello World”; char *p = &a[0];
Pointers and function arguments • Functions only receive copies of the variables passed to them. • A function needs to know the address of a variable if it is to affect the original variable • Large items like strings or arrays cannot be passed to functions either. • What is passed is the address of “hello world\n” in the memory. printf(“hello world\n”);
Swap Program #include <stdio.h> void swap(int *var1, int *var2); int main() { int a = 2; int b = 3; swap(&a, &b); printf("a = %d, b = %d\n", a, b); return 0; } void swap(int *var1, int *var2) { inttmp = *var1; *var1 = *var2; *var2 = tmp; }
2-Dimensional Arrays (Array of arrays) int d[3][2]; Access the point 1, 2 of the array:d[1][2] Initialize (without loops): int d[3][2] = {{1, 2}, {4, 5}, {7, 8}};
More about 2-Dimensional arrays A Multidimensional array is stored in a row major format. A two dimensional case: next memory element to d[0][3] is d[1][0] What about memory addresses sequence of a three dimensional array? next memory element to t[0][0][0] is t[0][0][1]
How to Calculate Array Address Locations For A[M][N] Array: M rows and N columns &A[i][j] A+N*i+j A[i][j] *(A+N*i+j)
Array Initialization CODE1 CODE2 for(j=0;j<N;j++) for(i=0;i<M;i++) A[i][j]=i*N+j; for(i=0;i<M;i++) for(j=0;j<N;j++) A[i][j]=i*N+j;
Pointer Arrays • int *ptrArray[10]; Array of 10 int pointers ptrArray[0]=&i; ptrArray[1]=&j; and so on … • char *charPtr[5]; Array of 5 char pointers • int (*p) [10] is different from int *p[10]; In int (*p) [10], p is a pointer to an array of 10 integers • int **pptr; pptr is a pointer to a memory location which holds pointer of an intmemero location
int main (void){ int (*p)[3]; // p is ptr to an arry of 3 ints int foo[3] = {0, 1, 2};p = foo;printf(" %d %d %d\n", (*p)[0], (*p)[1], (*p)[2]); /* It prints foo[0], foo[1], foo[2] */return 0;}
int* a, b; versus int *a, b; In both declarations, a is a pointer and b is an int Refer this link for more info on Pointers: http://www.slideshare.net/udekel/introduction-to-pointers-and-memory-management-in-c