0% found this document useful (0 votes)
10 views52 pages

C/C++ Array and Pointer Basics

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)
10 views52 pages

C/C++ Array and Pointer Basics

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

C/C++ Programming Techniques

Array and Pointer

Thanh-Hai Tran

Electronics and Computer Engineering


School of Electronics and Telecommunications
Hanoi University of Science and Technology
1 Dai Co Viet - Hanoi - Vietnam
Array (1D, 2D and multidimensional)

 Concept
 Declaration
 Indexing, Element access
 Initialization

Electronics and Computer Engineering


School of Electronics and Telecommunications
Hanoi University of Science and Technology
1 Dai Co Viet - Hanoi - Vietnam
Definition and declaration

 An array is a data structure containing a number of data


values, all of which have the same type
 These values, known as elements, can be selected by
their position within the array
 1D array is a simplest kind of array, its elements are
arranged one after another in a single row (or column)

 Declaration:
 int a[10];
 #define N 10
 int a[N];
 int a[]; //error
2020 3
Indexing and element access

 Array numbers are numbered starting from 0


 Elements of an array with N elements are indexed from 0
to N-1

 Access to an element of an array: a[i]


 Each element of array behave like a variable of type T

2020 4
Initialization of array
 int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 int a[10] = {1, 2, 3, 4, 5, 6}; //
{1,2,3,4,5,6,0,0,0,0}
 int a[10] = {0};//{0,0,0,0,0,0,0,0,0,0}
 int a[] = {1,2,3,4,5,6,7,8,9,10}; //10
elements

2020 5
Quick test
 Check the numbers for repeated digits

2020 6
Multidimensional array

 An array may have any number of dimensions


 2D array:
 int m[5][9]; the array a has 5 rows and 9 columns
 Both rows and columns are indexed from 0
 To access the element of m in row I and column j: m[i][j]

2020 7
Multidimensional array

 C stores arrays in row-major order, with row 0 first,


then row 1 and so forth

 We can create an initializer for a 2D array by nesting


1D initializers

2020 8
Multidimensional arrays

 The initializer will fill only the first three rows of m, the
last two rows will contain 0

 If an inner list isn't long enough to fill a row, the


remaining elements in the row are initialized to 0

2020 9
Initialization

 We even omit the inner braces, once the compiler has


seen enough values to fill one row, it begins filling the
next

2020 10
Using sizeof operator with arrays

 sizeof() determines the size of an array


 Example:
 int a[10];
 int s = sizeof(a);// s = 40 because each int
requires 4 bytes
 int n = size(a)/size(int); // number of
elements

2020 11
Constant arrays

 Any array, 1 or many dimensional can be made “constant”


by starting its declaration with keyword “constant”

 It documents that the program wont change the array, it


helps the compiler catch errors, by informing it that we
don’t modify array

2020 12
Limitations of array

 The array formed will be homogeneous. Thus no array


can have values of two data types.
 While declaring the array passing size of the array is
compulsory, and the size must be a constant. Thus there
is either shortage or wastage of memory.
 Insertion or deletion of elements in an array will require
shifting.
 The array does not check its boundaries: In C there is no
check to see if the values entered in the array are
exceeding the size of the array. Data entered with the
subscript exceeding the array size will be simply placed
outside the array, probably on the top of the data or the
program itself.

2020 13
Quick test – what is the output / error ?
1) int array[26],i;
for (i = 0; i<=25;i++) { array[i] = ‘A’ + i;
printf(“\n%d %c”,array[i], array[i]); }

2) int a[ 5] = {5,1,15,20,25}; int i,j,k =


1,m; i = ++a[1]; j = a[1]++; m = a[i++];
printf(“\n%d %d %d”,i,j,m);

3) int SIZE; scanf(“%d”,&SIZE);


int a[SIZE]; for( i = 1; i<=SIZE
;i++) {
scanf(“%d”,a[i]);
printf(“%d”,a[i]); }
2020 14
Pointer

 Introduction and Concept


 Declaration, operations
 void* and null pointer
 Pointer arguments
 Function arguments

Electronics and Computer Engineering


School of Electronics and Telecommunications
Hanoi University of Science and Technology
1 Dai Co Viet - Hanoi - Vietnam
Introduction

 A pointer is a special variable that is used to store the


address of some other variable.
 A pointer can be used to store the address of a single
variable, array, structure, union, or even a pointer.

2020 16
Why pointer ?

 Archive call by reference (i.e write functions which


change their parameters)
 Handle arrays efficiently
 Handle structures (Record) efficiently
 Create linked lists, trees, graphs etc.
 Put data onto the heap.
 Create tables of functions for handling windows events,
signals etc.
 Already been using pointers with scanf()
 Care must be taken when using pointers since there are
no safety features.
 But, one problem is that pointers have a bad reputation.
They are supposed to be difficult to use and understand.
2020 17
The concept of pointer

 Every variable is stored in the memory, Each memory


location has a numeric address.
 Example:
 int a = 5;
 Here a is the name of the variable, the value of the variable
is 5 while the address of the variable is 100 (assumed).

2020 18
Declaring pointers

 Pointers are declared by using star sign “*”


 Examples:
 int I; // Declare an integer
 int* p; // Declare a Pointer to an integer
 The two fundamental operators used with the pointers are
 Address operator &
 int a = 5;
 int*p = &a;// p points to a (p is initialized
by addresse of variable a)
 Indirection operator *
 To access what’s stored in the object
 printf(“%d”, *p); // 5
 int j = *&a; // j = a;

2020 19
Examples

 char c = 'A'; The addresses of the variables in memory in


int *pInt; ascending order are for illustration purposes
short s = 50; only. In fact, stacks allocated from high to
int a = 10; low => the following variable will have a
smaller address.
pInt = &a;
*pInt = 100;

Address 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511

Variable char c int* pInt short s int a …

Value 'A' 1507 50 100 …

pInt: 1507
*pInt: 100
&a: 1507
a: 100
2020 20
Example

2020
Attention

 Never apply the indirection operator to an uninitialzed


pointer variable

 Assigning a value to *p is particularly dangerous

2020 22
Pointer assignment
 int i, j, *p, *q;
 p = &i;
 q = p;
 *p = 1;
 *q = 2;

 p = &i; q = &j;
 i = 1;
 *q = *p;

2020 23
Pointers as arguments

 In a function call, a variable supplied as an argument is


protected against change because C passes arguments
by value
 This property of C can be a nuisance if we want the
function to be able to modify the variable
 Pointers offer a solution: instead of passing a variable x as
argument of a function, we’ll supply &x, a pointer to x.
 Example:

2020 24
Pointers as arguments

 When the function is called, the value 3.14159 is copied to


x, a pointer to i is stored in int_part and a pointer to d is
stored in frac_part
 When the function returns, I = 3; d = .14159

2020 25
Example

 Finding the largest and smallest numbers in an array

2020 26
Pointer void*

 The void * pointer is used for working with pure memory or


for manipulating undefined variables
memcpy (void * dest, const void * src, int size);
 void* Is a pointer but does not carry type information
 Can be implicitly converted to any other pointer type and
vice versa (but not in C ++)
 void * pVoid; int * pInt; char * pChar;
 pInt = pVoid; / * OK * /
 pChar = pVoid; / * OK * /
 pVoid = pInt; / * OK * /
 pVoid = pChar; / * OK * /
 pChar = pInt; /* error */
 pChar = (char *) pInt; / * OK * /
 Cannot use operator * with void * pointer
2020  * pVoid / * error * / 28
Pointer null
 NULL pointer is used to determine the validity of a pointer variable
 Is a pointer constant containing the value 0, type (void *), which has a
special meaning of not pointing to any address.
 The essence is a declared macro: #define NULL ((void *) 0)
 Cannot access the value of the device that pointer NULL pointing to
 cannot use operator * with pointer NULL
 int * pInt = NULL
 * pInt = 100; /* error */
 Need to distinguish pointer NULL (contains value 0) and pointer that
has not been initialized (contains random values / points to random
addresses)
 To avoid errors, always assign the pointer to NULL when not in use or
temporarily unavailable
 Comparing a pointer to NULL can also be omitted in logical
expressions: if (p! = NULL)… => if (p)…

2020 29
Operators with pointers
 Increase or decrease: is used to change the value of the pointer the
pointer will point to the next position (increase) or point to the previous
position (decrease). The increment / decrement value corresponds to
the pointer style size
Adress 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511

p-- short *p p++


(1502) (1504) (1506)
 Add / subtract address: also corresponds to the type it points to
Adress 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511

p-2 short *p p+3


(1500) (1504) (1510)
 Comparison: Two pointers of the same type can be compared with
each other as 2 integers (big, small, equal, ...)
 Subtraction: Two pointers of the same type can be subtracted to
produce the number of different elements (signed). 30
2020
Pointer and Array

Electronics and Computer Engineering


School of Electronics and Telecommunications
Hanoi University of Science and Technology
1 Dai Co Viet - Hanoi - Vietnam
Pointer and array
 Array is a static pointer (address cannot be changed).
 int x;
 int arr [] = {1, 2, 3, 4, 5};
 arr = & x; /* error */
 When used as a pointer, the array name corresponds to the pointer name of
the first element of the array, the type of the pointer is the type of the element
of the array => Can manipulate the array type variable as manipulating the
pointer.
 int arr [] = {1, 2, 3, 4, 5};
 int x;
 * arr = 10; / * as: arr [0] = 10; * /
 printf ("% d", * (arr + 2)); / * arr [2] * /
 Pointers can also be manipulated as arrays
 int * p = arr;
 p [2] = 20; / * as: arr [2] = 20; * /
 p = arr + 2; / * as: p = & arr [2]; * /
 p [0] = 30; / * as: arr [2] = 30; or: * p = 30; * /
 Conclusion: pointers and arrays can be used interchangeably,
2020 depending on the case that used for convenience 32
Pointer and Array (difference)

 A new address cannot be assigned to an array variable


 The array variable is allocated memory for the elements (in
the stack) right from the time of declaration
 sizeof () with array returns the actual size of the array (sum
of elements), sizeof () with the pointer returns the size of the
pointer itself (size integer type)
 float arr [5]; Sizeof (arr) returns 20 (5 * 4)
 float * p = arr; Sizeof (p) returns 4 (on a 32-bit system).
 sizeof (arr) / sizeof (arr [0]) // the number of elements in the array
 Negative indexes are available where the pointer is used as
an array:
 int arr [] = {1, 2, 3, 4, 5};
 int * p = arr + 2;
 p [-1] = 10; / * as: arr [1] = 10; * /
2020 33
Pointer to pointer

 A pointer can point to another pointer


 float x = 1.5;
float *pX = &x; /* pX trỏ đến x */
float **ppX = &pX; /* ppX trỏ đến pX */
printf("%f", **ppX); /* in ra giá trị 1.5 */

ppX pX x
1.5

**ppX = 2.3;

ppX pX x
2.3

 Similar to 2-dimensional array (or array of arrays,


pointers to arrays, array of pointers)

2020 34
string
 Array of character, terminates by character '\0'
1. char ten[10] = "Tung"; (initialized array by a pointer)
2. char ten[10] = {'T', 'u', 'n', 'g', '\0' }; (by array)
/* sizeof(ten) == 10 */
3. char *ten = “VietTung"; (initialize pointer by a pointer)
/* sizeof(ten) == 4, trên hệ 32 bit */
4. char *ten = {'T', 'u', 'n', 'g', '\0' }; /* wrong */
 Compute the length of a string:
 for (n=0; *s; n++, s++) ;
 Some common operators
 #include <string.h>
 int strlen(s)  tính độ dài chuỗi s
 char *strcpy(dst, src) copy chuỗi src sang chuỗi dst, trả về con trỏ đến
dst
 char *strcat(s1, s2) nối chuỗi s2 vào chuỗi s1, trả về con trỏ đến s1
 int strcmp(s1, s2) so sánh chuỗi s1 với s2 (s1-s2), kết quả: >0, =0, <0
 char *strstr(s1, s2) tìm vị trí chuỗi s2 trong s1
2020 35
Dynamic memory allocation
 Usually, variables are allocated memory when creating / when
declared => statically allocated (stored in the stack).
 Variable memory allocation (only known when running the program)
=> dynamic allocation (stored in the heap)
 #include <stdlib.h>
 void * malloc (int size) / * size: number of bytes to
allocate * /
 int * p = (int *) malloc (10 * sizeof (int)); / *
level 10 int * /
 void * calloc (int num_elem, int elem_size)
 void * realloc (void * ptr, int size)
 The allocation may fail and return NULL which needs
checking
 Cancel (return) the allocated memory:
 void free (void * p);
 free (p);

2020 36
Pointer to struct, union

 With a pointer to a struct or union, the “->" operator


can be used to access member variables instead of
"*" and ".“
 p->member tương đương với (*p).member
 Example:
 typedef struct {
int x, y;
} Point;
Point *pP = (Point*)malloc(sizeof(Point));
pP->x = 5; /* as: (*pP).x = 5; */
(*pP).y = 7;/* as: pP->y = 7; */

2020 37
Attention

 In normal applications, the program cannot access


other than its allocated memory => Must control
which address the pointer points to.
 Consequent:
 Do not use a pointer that has not been initialized , so it is a
habit to assign the pointer by NULL when it is not used or
not, so that it can be checked later.
 Addresses only the created variables (static variables or
allocated memory) to the pointer to ensure the pointer
always points to a valid memory area.
 Must check the length of the memory that the pointer points
to so that it cannot be accessed over (buffer overflow error).
 When the allocated memory is no longer in use, it must be
discarded so that it can be used again
2020 38
Function Pointer in C
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{ P F()
printf("Value of a is %d\n", a);
}
int main()
{ P = F;
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun; P();

/* The above line is equivalent of following two


void (*fun_ptr)(int);
fun_ptr = &fun;
*/

// Invoking fun() using fun_ptr


(*fun_ptr)(10);

return 0;
2020} 39
Example
#include <stdio.h> void main(){
float (*f)(float[], int ); int const n = 100;
//Khai báo float k[n], i, m;
float sum(float a[], int N){ do {
int i; for (i=0;i<n;i++) k[i] =
float s = 0; 0.5*rand(2*n);
for (i=0;i<N;i++) s += a[i]; for (i=0;i<n;i++)
return s; printf("%0.2f ", k[i]);
} printf("\n");
float product(float a[], int printf("Chon tinh tong
N){ (0) hay tich (1) cua day hay
int i; thoat (khac):");
float s = 1; scanf("%d",&m);
for (i=0;i<N;i++) s *= a[i]; if (m == 0) f = sum;
//Gán con trỏ
return s;
else if (m == 1) f =
} product;
else break;
printf("Ket qua: %f \n",
f(k,n)); //Gọi hàm
2020 } while (m == 0 || m == 1);
Exercises

 WAP to call a function pointer to compare two integers, return


the bigger value int* findLarger(int *n1, int
 Solution *n2)
{
#include <stdio.h>
int* findLarger(int*, int*); if(*n1 > *n2)
void main() return n1;
{ else
int numa=0; return n2;
int numb=0; }
int *result;
printf("\n\n Pointer : Show a function returning pointer :\n");
printf("--------------------------------------------------\n");
printf(" Input the first number : ");
scanf("%d", &numa);
printf(" Input the second number : ");
scanf("%d", &numb);
result=findLarger(&numa, &numb);
2020
printf(" The number %d is larger. \n\n",*result); 43
Using pointer for Array Processing

 #define N 10
 int a[N], sum, *p;
 sum = 0;
 for(p=&a[0]; p<&a[N];p++)
 Sum += *p;

2020 44
Combining the * and ++ operators

 a[i++] = j;
 *p++ = j; // *(p++) = j;

2020 45
Array arguments

 When passed to a function, an array name is always


treated as a pointer.

 Suppose we call find_largest as follows:

 This call causes a pointer to the first element of b to be


signed to a; the array itself is not copied 46
2020
Array arguments

 When an ordinary variable is passed to a function, its


value is copied, any change to the corresponding
parameter don’t affect the variable
 In contrast, an array used as argument is not protected
again change, since no copy is made of the array itself
 For example: the following function will modify an array by
storing zero to each of its elements

2020 47
Array arguments

 To indicate that an array parameter wont change, we


include the word “const”

 The time required to pass an array to a function doesn't


depend on the size of the array since copy of array is
made
 An array parameter can be declared as a pointer if
desired.

2020 48
Pointers and Multidimensional arrays

2020 49
Quick test

2020 50
Quick test

2020 51
Exercise

2020 52
Summary

 Array
 1D, 2D, ND
 Main operations: declaration, access
 Pointer
 Main operations: declaration, address, access,
increase/decrease
 Compare with array
 Function pointer

2020 53
Exercises

 WAP to sort a 1-d array using selection sort


 WAP that merges two sorted arrays a and b to make a
sorted array c
 WAP to find maximum and the minimum values from a set
of values stored in an array, along with their positions in
the array.
 WAP that read an image from file / webcam (using
openCV). Compute and display the histogram (grayscale
or color) of the image.

2020 54
References

 Slide, C/C++ Programming technique, Dao Trung Kien


 Slide, C/C++ Programming technique, Nguyen Thanh
Binh
 Chapter 12, Pointers & Arrays, C programming – A
Modern approach

2020 55

You might also like