KEMBAR78
ARRAY, String and Pointers | PDF | Object Oriented Programming | Computer Engineering
0% found this document useful (0 votes)
4 views37 pages

ARRAY, String and Pointers

Uploaded by

cudarun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views37 pages

ARRAY, String and Pointers

Uploaded by

cudarun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

ARRAY

• An array is a variable that can store multiple


values of the same type.
• The number used to refer to a particular element
of an array is called its index or subscript.
• Declaration for an array in C++ syntax is:
datatype arrayName[size];
• int A[5];
• int - type of element to be stored
• x - name of the array
• 6 - size of the array
1
ARRAY DECLARATION
• The array size used to declare an array must be a constant
expression in standard C++.
• For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong
• But it is all right if SIZE is a constant as follows:
const int SIZE = 4;
double myList[SIZE]; // Correct
• If arrays have the same element type, they can be declared
together that are separated by commas. For example,
double listA[10], listB[25];
2
Array Initialization
•We can assign values to members of an array at the point of declaration
using the following syntax:
type arrayName[arraySize] = {value0, value1, ..., value k};
• For example, int A[5] = {11, 3, 5, 7, 9};
• This is called the array initializer, declares and initializes the array A
with 5 elements in a single statement, making it equivalent to the
statements shown below:
int A[5];
A[0] = 11;
A[1] = 3;
A[2] = 5;
A[3] = 7;
A[4] = 9;
3
Array Initialization

4
Accessing Array Elements
• Each element in the array is represented using the following syntax:
arrayName[index];

• For example, storing 75 in the third element of


array A:
A[2] = 75;
• And passing the third element of A value to the
variable a, we could write:
a = A[2];

• We can use loop to manipulate/process an array.


5
Accessing an array element
#include <iostream>
using namespace std;
OUTPUT
int main() Value: 5

{
int bill[7]={3,4,5,6,7,7,6};
cout << " value: "<< bill[2];
return(0);
}

6
• No Array-to-Array Assignments
You cannot assign one array to another in C++.
The following is wrong:
int a[10], b[10];
// Now, assign all elements of
// array b to array a
a = b; // error – illegal
Instead, you have to do the assignments for each element:
int i;
// Now, assign all elements of
// array b to array a
for(i=0; i<10; i++) a[i] = b[i];
7
DISPLAYING ARRAY ELEMENTS
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are: ";
cout << "\nThe numbers are: ";
// Printing array elements OUTPUT
// using traditional for loop The numbers are: 7 5 6 12 35

for (int i = 0; i < 5; ++i) {


cout << numbers[i] << " ";
}
return 0;
}

8
Take Inputs from User and Store Them in an Array
#include <iostream>
using namespace std;
int main() {
int numbers[5];
cout << "Enter 5 numbers: " << endl;
// store input from user to array
for (int i = 0; i < 5; ++i) { OUTPUT
cin >> numbers[i]; Enter 5 numbers:
} 11
cout << "The numbers are: "; 12
13
// print array elements
14
for (int n = 0; n < 5; ++n) { 15
cout << numbers[n] << " "; The numbers are: 11 12 13 14 15
}
return 0;
}

9
MULTIDIMENSIONAL ARRAY
• An array of an array, known as a
multidimensional array.
• For example:
int a[3][4];

10
Initializing Two-Dimensional Arrays
• Multidimensional arrays may be initialized by specifying
brackets values for each row.
• Following is an array with 3 rows and each row has 4
columns.
• int a[3][4] = {
{3, 1, 2, 3} , /* initializers for row indexed by 0 */
{0, 7, 6, 5} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
• Or alternatively we can initialize as:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
11
Accessing Two-Dimensional Array Elements
• An element in 2-dimensional array is accessed by
using the subscripts, i.e., row index and column
index of the array.
• For example:
int val = a[2][3];
• The above statement will take 4th element
from the 3rd row of the array.

12
// C++ Program to display all elements
// of an initialised two dimensional array
#include <iostream>
using namespace std;
int main() { OUTPUT
int test[3][2] = {{2, -5}, test[0][0] = 2
{4, 0}, test[0][1] = -5
{9, 1}}; test[1][0] = 4
// use of nested for loop test[1][1] = 0
// access rows of the array test[2][0] = 9
test[2][1] = 1
for (int i = 0; i < 3; ++i) {
// access columns of the array
for (int j = 0; j < 2; ++j) {
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}
return 0;
}

13
String
• String is a collection of characters.
• There are two types of strings commonly used in
C++ programming language:
– Strings that are objects of string class (The Standard
C++ Library string class)
– C-strings (C-style Strings)

14
C-Style Character String
• The C-style character string originated within the C
language and continues to be supported within C++.
• This string is actually a one-dimensional array of
characters which is terminated by a null character '\0'.
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
• If you follow the rule of array initialization, then you
can write the above statement as follows:
• char greeting[] = "Hello";
• Following is the memory presentation of above defined
string in C/C++:

15
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl;
cout << "\nEnter another string: ";
cin >> str;
cout << "You entered: "<<str<<endl;
return 0;
OUTPUT
} Enter a string: C++
You entered: C++
Enter another string: Programming is fun.
You entered: Programming
16
• Problem: Entering the string “Programming is
fun”, the above program only returns
“Programming”, not the entire sentence.
• Reason: The C++ input/output system stops
reading a string when the first whitespace
character is encountered.
• Solution: Use another C++ library function,
gets().

17
#include <iostream>
using namespace std;
#include <cstring>
int main()
{
char str[80]; // long enough for user input?
cout << "Enter a string: ";
gets(str); // read a string from the keyboard
cout << "Here is your string: ";
cout << str << endl;
return(0);
}

OUTPUT
Enter a string: Jimma institute of technology
Here is your string: Jimma institute of technology
18
Some C++ Library Functions for Strings

• C++ supports a range of string-manipulation


functions.
• The most common are:
•strcpy() : copy characters from one string to another
•strcat() : concatenation of strings
•strlen() : length of a string
•strcmp() : comparison of strings
• First of all, include <string.h> or include <cstring>
in the very first lines of the code.
19
Continued
• strcpy(to_string, from_string) — String Copy :

#include <iostream>

using namespace std;

#include <cstring>

int main() OUTPUT


{ hello
char a[10];

strcpy(a, "hello");

cout << a;

return(0);

20
#include <iostream>
using namespace std;
#include <cstring>
int main()
{
char a[10] = "hello";
char b[10] = "JIT";
cout<<b<<endl; OUTPUT
strcpy(b, a); JIT
hello
cout << a<<endl; hello
cout<<b<<endl;
return(0);
}

21
• strlen(string) — String Length : Continued
#include <iostream>

using namespace std; strlen(str) returns the length of the


#include <cstring> string pointed to by str, i.e., the number
of characters excluding the null
int main()
terminator.
{

char str[80];

cout << "Enter a string: ";

gets(str); // let the input is: hello


OUTPUT
// Length is: 5 Enter a string: program
Length is: 7
cout << "Length is: " << strlen(str);

return(0);

}
22
Continued
• strcat(string_1, string_2) — Concatenation of Strings :
#include <iostream>

using namespace std; The strcat(s1,s2) function


#include <cstring> appends s2 to the end of s1.
int main(){ String s2 is unchanged.
char s1[21], s2[11];

strcpy(s1, "Hello");

strcpy(s2, " there");


Displays:
strcat(s1, s2);

cout << s1 << endl; Hello there


cout << s2 << endl; there
return(0);

23
Continued

The first string array has to be large enough to hold both strings:

• To be on the safe side:


strlen(s1concats2) >= strlen(s1) + strlen(s2)

24
Continued

• strcmp(string_1, string_2) — Comparison of Strings :

The strcmp(str_1, str_2) function compares two strings and


returns the following result:
• str_1 == str_2 :0
• str_1 > str_2 : positive number
• str_1 < str_2 : negative number
The strings are compared lexicographically
(i.e., according to dictionary order), for example:
a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca
< abd

25
// Comparing strings
// Comparing strings
Continued
#include <iostream>

using namespace std;


OUTPUT
#include <cstring> Enter password: hai
Invalid password.
int main(){

char str[80];
Enter password: password
cout << "Enter password: "; Logged on.
gets(str);

if(strcmp(str, "password")) // strings differ

cout << "Invalid password.\n";

else cout << "Logged on.\n";

return(0);

}
26
POINTERS

27
Address in C++
• To understand pointers, you should first know how data is stored
on the computer.
• Each variable is assigned a location in the computer's memory.
The value the variable stores is actually stored in the location
assigned.
• To know where the data is stored, C++ has an ampersand ‘&’
symbol.
• The & reference operator gives you the address occupied by a
variable.
• If var is a variable then, &var gives the that variable.

28
Example 1: Address in C++
#include <iostream> Output:
using namespace std; 0x7fff5fbff8ac
0x7fff5fbff8a8
0x7fff5fbff8a4
int main()
{ Note: You may not get the same result on your
int var1 = 3; system.
int var2 = 24;
int var3 = 17; The 0x in the beginning represents the
address is in hexadecimal form.
cout << &var1 << endl;
Notice that first address differs from second by
cout << &var2 << endl; 4-bytes and second address differs from third
cout << &var3 << endl; by 4-bytes.

return 0; This is because the size of integer (variable of


} type int) is 4 bytes in 64-bit system.

29
Pointer Definition
• Pointers are used in C++ program to access the memory and
manipulate the address.
• For type T, T* is the type “ ”
• For example:

30
C++ Pointers Declarations
• Pointers variables are variables that points to a specific address in the
memory pointed by another variable.
• For example: int *p; int*p,*q;
// or, // for many pointers
int* p; int* p, q;

• The statement above defines a pointer variable p, which holds the


memory address.
• The asterisk ‘*’ is a dereference operator which means pointer to.
• Here, pointer p is a pointer to int, i.e., it is
in the memory address.
• If ptr is a pointer then, *ptr gives the that address.

31
C++ Pointers
#include <iostream>
using namespace std;
int main(){
int *pc, c;
c = 5;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
pc = &c; // Pointer pc holds the memory address of variable c
cout << "Address that pointer pc holds (pc): "<< pc << endl;
cout << "Content of the pointer pc holds (*pc): " << *pc << endl << endl;
c = 11; // The content inside memory address &c is changed from 5 to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the pointer pc holds (*pc): " << *pc << endl << endl;
*pc = 2;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
return 0;
}

32
 When c = 5; the value 5 is stored in the address of variable c -
0x7fff5fbff8c.
 When pc = &c; the pointer pc holds the address of c -
0x7fff5fbff8c, and the expression (dereference operator) *pc
outputs the value stored in that address, 5.
 When c = 11; since the address pointer pc holds is the same as c
- 0x7fff5fbff8c, change in the value of c is also reflected when the
expression *pc is executed, which now outputs 11.
 When *pc = 2; it changes the content of the address stored by
pc - 0x7fff5fbff8c. This is changed from 11 to 2. So, when we
print the value of c, the value is 2 as well.

Address of c (&c): 0x7fff5fbff80c


Output:
Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 2
33
Be careful !!!
Suppose, you want pointer pc to point to the address of c. Then,
int *pc, c = 5;
pc=c; // Wrong! pc is address whereas, c is not an address.
*pc=&c; // Wrong! *pc is the value pointed by address, but &c is an
address.

// In both of the above cases, pointer pc is not pointing to the address of c.

pc=&c; // Correct! pc is an address and, &c is also an address.


*pc=c; // Correct! *pc is the value pointed by address and, c is also a
value.

// In both of the above cases, pointer pc is pointing to the address of c.

int* pc2 = &c; // Correct! pc2 is address pointer, and &c is also
address.
int *pc3 = &c; // Correct! pc3 is address pointer, and &c is also
address.
34
Pointers and Arrays
• Not only can pointers store address of a single variable, it can
also store address of cells of an array.
int *ptr;
int arr[5]; int *ptr;
// store the address of the first int arr[5];
// element of arr in ptr ptr = &arr[0];
ptr = arr;
• Here, ptr is a pointer variable while arr is an int array. The
code ptr = arr; stores the address of the first element of the
array in variable ptr.
• arr and &arr[0] both are the same
• Addresses for the rest of the array elements are given
by &arr[1], &arr[2], &arr[3], and &arr[4].
Pointers and Arrays
• For example: int* ptr;
int a[5] = {2,4,6,8,10};
// &a[2] is the address of third element of
a[5].
ptr = &a[2];
// ptr + 1 increases by the size of int (4B in
64-bit)
// ptr + 1 will point to the fourth element.
cout<< *ptr + 1; // displays: 8
a[0] a[1] a[2] a[3] a[4] int *ptr2 = &a; // char is 1B,
2 4 6 8 10
// ptr2 is pointing to a[0]
cout<< *ptr2 + 4; // displays:10
ptr2 ptr ptr + 1

36
Example Pointers and Arrays
#include <iostream> Displaying address using arrays:
&arr[0] = 0x7fff5fbff880
using namespace std; &arr[1] = 0x7fff5fbff884
#define SIZE 3 &arr[2] = 0x7fff5fbff888

int main(){ Displaying address using pointers:


float arr[SIZE]; ptr + 0 = 0x7fff5fbff880
float *ptr; ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
int i;
cout << "Displaying address using arrays: " << endl;
for (i = 0; i < SIZE; ++i)
cout << "&arr[" << i << "] = " << &arr[i] << endl;
// ptr = &arr[0]
ptr = arr;
cout<<"\nDisplaying address using pointers: "<< endl;
for (i = 0; i < SIZE; ++i)
cout << "ptr + " << i << " = "<< ptr + i << endl;
return 0;
}
37

You might also like