0% found this document useful (0 votes)
102 views26 pages

CH-230-A Programming in C and C++ C/C++: Dr. Kinga Lipskoch

The document discusses pointers and dynamic memory allocation in C/C++. It explains how to allocate memory for multi-dimensional arrays using pointers to pointers. Specifically, it shows how to declare a "char **table" pointer to allocate an array of char pointers, with each pointer then allocating memory for a row of char elements. This allows variably sized multi-dimensional arrays to be created and accessed using table[i][j] syntax, with the address calculated as *(table + (i * COL + j)).

Uploaded by

Memet Eden
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)
102 views26 pages

CH-230-A Programming in C and C++ C/C++: Dr. Kinga Lipskoch

The document discusses pointers and dynamic memory allocation in C/C++. It explains how to allocate memory for multi-dimensional arrays using pointers to pointers. Specifically, it shows how to declare a "char **table" pointer to allocate an array of char pointers, with each pointer then allocating memory for a row of char elements. This allows variably sized multi-dimensional arrays to be created and accessed using table[i][j] syntax, with the address calculated as *(table + (i * COL + j)).

Uploaded by

Memet Eden
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/ 26

CH-230-A

Programming in C and C++


C/C++

Lecture 4

Dr. Kinga Lipskoch

Fall 2019
Dynamic Memory Allocation Projects Libararies

Pointers and Arrays

I Ex: char array[5];


char *array_ptr1 = &array[0];
char *array_ptr2 = array;
// the same as above
I C allows pointer arithmetic:
I Addition
I Subtraction
I *array_ptr equivalent to array[0]
I *(array_ptr+1) equivalent to array[1]
I *(array_ptr+2) equivalent to array[2]
I What is (*array_ptr)+1?

C/C++ Fall 2019 2 / 26


Dynamic Memory Allocation Projects Libararies

Locating a Matrix Element in the Memory

I Consider the following


int table[ROW][COL];
where ROW and COL are constants
I table holds the address of the pointer to the first element
I *table holds the address of the first element
I What is the address of table[i][j]?
*(table + (i * COL + j))
I Find out the formula for an arbitrary multidimensional array

C/C++ Fall 2019 3 / 26


Dynamic Memory Allocation Projects Libararies

Pointer Arithmetic with Arrays


1 # include < stdio .h >
2 # define ROW 2
3 # define COL 3
4 int main () {
5 int arr [ ROW ][ COL ] = { {1 , 2 , 3} , {11 , 12 , 13} };
6 int i = 1;
7 int j = 2;
8 int * p = ( int *) arr ; // needs explicit cast
9 printf ( " Address of [1][2]: % p \ n " , & arr [1][2]) ;
10 printf ( " Address of [1][2]: % p \ n " , p + ( i * COL + j ) ) ;
11 printf ( " Value of [1][2]: % d \ n " , arr [1][2]) ;
12 printf ( " Value of [1][2]: % d \ n " , *( p + ( i * COL + j ) ) ) ;
13 printf ( " \ n " ) ;
14 printf ( " Address of [0][0]: % p \ n " , p + (0 * COL + 0) ) ;
15 printf ( " Address of [0][1]: % p \ n " , p + (0 * COL + 1) ) ;
16 printf ( " Address of [0][2]: % p \ n " , p + (0 * COL + 2) ) ;
17 printf ( " Address of [1][0]: % p \ n " , p + (1 * COL + 0) ) ;
18 printf ( " Address of [1][1]: % p \ n " , p + (1 * COL + 1) ) ;
19 printf ( " Address of [1][2]: % p \ n " , p + (1 * COL + 2) ) ;
20 return 0;
21 }
C/C++ Fall 2019 4 / 26
Dynamic Memory Allocation Projects Libararies

Variably Sized Multidimensional Arrays

I Unidimensional arrays can be allocated ”on the fly” using the


malloc() function
I Possible also for multidimensional arrays, but more tricky
I Underlying idea: a pointer can point to the first element of a
sequence
I A pointer to a pointer can then point to the first element of a
sequence of pointers
I And each of those pointers can point to first element of a
sequence

C/C++ Fall 2019 5 / 26


Dynamic Memory Allocation Projects Libararies

Pointers to Pointers for Multidimensional Arrays (1)

I Consider the following table


char **table; char *
char *
I We can make table to point to an array of char *
pointers to char char *
table = (char **) malloc(sizeof(char *) char *
* N); char *
char *
I Every element in the array of N rows is a char *
char* char *

C/C++ Fall 2019 6 / 26


Dynamic Memory Allocation Projects Libararies

Pointers to Pointers for Multidimensional Arrays (2)

I Every pointer in the array can in turn point to an array


I In this way a two-dimensional array with N rows and M
columns has been allocated

1 for ( i = 0; i < N ; i ++)


2 table [ i ] = ( char *) malloc ( sizeof ( char ) * M ) ;

C/C++ Fall 2019 7 / 26


Dynamic Memory Allocation Projects Libararies

Pointers to Pointers for Multidimensional Arrays (3)


char **table

char * char char char char char


char *
char *
char *
char *
char *
char *
char *
char *

To access a generic element in the dynamically allocated matrix a


matrix-like syntax can be used. Let us see why ...

C/C++ Fall 2019 8 / 26


Dynamic Memory Allocation Projects Libararies

Allocating Space for a Multidimensional Array (1)


Memory
char
char
char
0x3000 char
char **table char
char
char
char* char
char
char* char
char
char* char
char* char
char
char
char
char
char
char
char
char
char
Case i=0 char
char
1 for ( i = 0; i < 4; i ++)
2 table [ i ] = ( char *) malloc ( sizeof ( char ) * 5) ;

C/C++ Fall 2019 9 / 26


Dynamic Memory Allocation Projects Libararies

Allocating Space for a Multidimensional Array (2)


Memory
char
char
char
0x3000 char
char **table char
char
char
char* char
0x3005 char
char* char
char
char* char
char* char
char
char
char
char
char
char
char
char
char
Case i=1 char
char
1 for ( i = 0; i < 4; i ++)
2 table [ i ] = ( char *) malloc ( sizeof ( char ) * 5) ;

C/C++ Fall 2019 10 / 26


Dynamic Memory Allocation Projects Libararies

Allocating Space for a Multidimensional Array (3)


Memory
char
char
0x3000
char
char **table char
char
char
char
char* char
0x3005 char
char* char
char
char* char
char* char
0x3010 char
char
char
char
char
char
char
char
char
Case i=2 char
char
1 for ( i = 0; i < 4; i ++)
2 table [ i ] = ( char *) malloc ( sizeof ( char ) * 5) ;

C/C++ Fall 2019 11 / 26


Dynamic Memory Allocation Projects Libararies

Allocating Space for a Multidimensional Array (4)


Memory
char
char
char
0x3000 char
char **table char
char
char
char* char
0x3005 char
char* char
char
char* char
char* char
0x3010 char
char
char
char
char
0x3015 char
char
char
char
Case i=3 char
char
1 for ( i = 0; i < 4; i ++)
2 table [ i ] = ( char *) malloc ( sizeof ( char ) * 5) ;

C/C++ Fall 2019 12 / 26


Dynamic Memory Allocation Projects Libararies

Drawing Memory in a Different Way: The Result is a Table

char **table

char* char char char char char


char* char char char char char
char* char char char char char
char* char char char char char

1 for ( i = 0; i < 4; i ++)


2 table [ i ] = ( char *) malloc ( sizeof ( char ) * 5) ;

C/C++ Fall 2019 13 / 26


Dynamic Memory Allocation Projects Libararies

De-allocating a Pointer to Pointer Structure

I Everything you have allocated via malloc() must be


de-allocated via free()
I Ex: De-allocation of a 2D array with N elements

1 int i ;
2 for ( i = 0; i < N ; i ++)
3 free ( table [ i ]) ;
4 free ( table ) ;

C/C++ Fall 2019 14 / 26


Dynamic Memory Allocation Projects Libararies

Working with 2D Dynamic Arrays


1 # include < stdio .h >
2 # include < stdlib .h >
3 void s e t _ a l l _ e l e m e n t s ( int ** arr , int numrow , int numcol ) {
4 int r , c ;
5 for ( r = 0; r < numrow ; r ++)
6 for ( c = 0; c < numcol ; c ++)
7 arr [ r ][ c ] = r * c ; // some value ...
8 }
9 int main () {
10 int ** table , row ;
11 table = ( int **) malloc ( sizeof ( int *) * 3) ;
12 if ( table == NULL )
13 exit (1) ;
14 for ( row = 0; row < 3; row ++) {
15 table [ row ] = ( int *) malloc ( sizeof ( int ) * 4) ;
16 if ( table [ row ] == NULL )
17 exit (1) ;
18 }
19 s e t _ a l l _ e l e m e nt s ( table , 3 , 4) ;
20 }

C/C++ Fall 2019 15 / 26


Dynamic Memory Allocation Projects Libararies

Static vs. Dynamic Array Allocation (1)

I int a[n][m] leads to an index offset calculation using the


known array dimensions
I int **a treats a as an array int *[] and once indexed the
result as an array of int []
I Statically allocated arrays occupy less memory
I Pointers to pointers allow tables where every row can have its
own dimension
I One can have pointers to pointers to pointers (e.g., int ***)
to have 3D data structures

C/C++ Fall 2019 16 / 26


Dynamic Memory Allocation Projects Libararies

Static vs. Dynamic Array Allocation (2)


I Static allocation
I int a[100][50]; int b[n][m];
I Syntax for allocation is easy
I Release/reallocation not possible at runtime
I Allocated memory is contiguous
I Dynamic allocation
I int **a; int *b[100], int ***c; ...
I Call(s) of malloc is needed
I Syntax for allocation is more difficult
I Release/reallocation possible at runtime using free, realloc
I Allocated memory can be, but in general is not contiguous
I Passing arrays to functions: static_dyn_allocation.c
I Further reading/study:
https://www.cse.msu.edu/~cse251/lecture11.pdf
C/C++ Fall 2019 17 / 26
Dynamic Memory Allocation Projects Libararies

The const Keyword

I The modifier const can be applied to variable declarations


I It states that the variable cannot be changed
I i.e., it is not a variable but a constant
I When applied to arrays it means that the elements cannot be
changed

C/C++ Fall 2019 18 / 26


Dynamic Memory Allocation Projects Libararies

const Examples

1 const double e = 2.718 281828 45905;


2 const char str []= " Hello world " ;
3 e = 3; /* error */
4 str [0] = ’h ’; /* error */

I You can also use #define of the preprocessor


I But defines do not have type checking, while constants do

C/C++ Fall 2019 19 / 26


Dynamic Memory Allocation Projects Libararies

More const Examples

I const char *text = "Hello";


I Does not mean that the variable text is constant
I The data pointed to by text is a constant
I While the data cannot be changed, the pointer can be changed
I char *const name = "Test";
I name is a constant pointer
I While the pointer is constant, the data the pointer points to
may be changed
I const char *const title = "Title";
I Neither the pointer nor the data may be changed

C/C++ Fall 2019 20 / 26


Dynamic Memory Allocation Projects Libararies

Dealing with Big Projects

I Functions are a first step to break big programs in small


logical units
I A further step consists in breaking the source into many files
I Smaller files are easy to handle
I Objects sharing a context can be put together and easily reused
I C allows to put together separately compiled files to have one
executable

C/C++ Fall 2019 21 / 26


Dynamic Memory Allocation Projects Libararies

Declarations and Definitions

I Declaration: introduces an object. After declaration the


object can be used
I Example: functions’ prototypes
I Definition: specifies the structure of an object
I Example: function definition
I Declarations can appear many times, definitions just once

C/C++ Fall 2019 22 / 26


Dynamic Memory Allocation Projects Libararies

Building from Multiple Sources

I C compilers can compile multiple sources files into one


executable
I For every declaration there must be one definition in one of
the compiled files
I Indeed also libraries play a role
I This control is performed by the linker
I gcc -o name file1.c file2.c file3.c

C/C++ Fall 2019 23 / 26


Dynamic Memory Allocation Projects Libararies

Libraries

I Libraries are collection of compiled definitions


I You include header files to get the declarations of objects in
libraries
I At linking time libraries are searched for unresolved
declarations
I Some libraries are included by gcc even if you do not
specifically ask for them

C/C++ Fall 2019 24 / 26


Dynamic Memory Allocation Projects Libararies

Linking Math Functions: Example


1 # include < math .h >
2 # include < stdio .h >
3
4 int main () {
5 double n ;
6 double sn ;
7

8 scanf ( " % lf \ n " , & n ) ; /* double needs % lf */


9 sn = sqrt ( n ) ;
10 /* conversion from double to float ok */
11 printf ( " Square root of % f is % f \ n " , n , sn ) ;
12 return 0;
13 }
14
15 gcc - lm -o compute compute . c

C/C++ Fall 2019 25 / 26


Dynamic Memory Allocation Projects Libararies

Compilers, Linkers and More

I Different compilers differ in many details


I Libraries names, ways to link against them, types of linking
I Check your documentation
I But preprocessing, compilation and linking are common steps

C/C++ Fall 2019 26 / 26

You might also like