Professional Documents
Culture Documents
C - Pointers, Arrays and Memory Management
C - Pointers, Arrays and Memory Management
C - Pointers, Arrays and Memory Management
1
Content
• 2.1. Array
• 2.1.1. Array variable types
• 2.1.2. Multidimensional arrays
• 2.1.3. Strings
• 2.2. Pointers
• 2.2.1. Pointer variable types
• 2.2.2. Pointers vs arrays
• 2.2.3. Dynamic Memory allocation
2
2.1. Array
3
2.1.1. Array variable types
Array name
Index
Declaration and Initialization
int a[10];
Declaration and Initialization
• 1D array
char s[20];
char s[10] = {‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’};
char s[10] = “string”; // char s[10] = {’s’,’t’,’r’,’i’,’n’,’g’,’\0’};
7
Indexing and element access
8
Example:
Program to sort an array of N numbers in ascending order using bubble sort algorithm
main(){
const int N = 200 ;
float a[N] ;
int i,j ;
… // input values for array a ;
for (i=0;i<N-1;i++)
for (j=0;j<N-i-1;j++)
if (a[j]>a[j+1]) {
float tg = a[j];
a[j]=a[j+1];
a[j+1] =tg;
}
… // print the result
}
2.1.2. Multidimensional array
10
2.1.2. Multidimensional array
• C stores arrays in row-major order, with row 0 first, then row 1 and so on
// The initializer fills only the first three rows of m, the last two rows
will contain 0
char s [2][3];
// int a[2][3] = {1,2,3,4,5,0};
int a[][3] = {1,2,3,4,5};
int a[2][3] = {{1,2},{3,4,5}}; // int a[2][3] = {{1,2,0},{3,4,5}};
17
2.1.3. C-String
• #include <stdio.h>
scanf("%s", ten) Read until you encounter a space
scanf("%[^\n]", ten); include spaces, read to enter character
gets(name);
• #include <string.h>
int strlen(s) calculate string length
int strcmp(str1, str2) compare 2 strings, result: 1, 0, -1
char* strcpy(dest, src) copy src (upto \0) to dest
char ntca[10];
ntca = “bob”; //No, illegal!!
strcpy(ntca, “bob”); // ok
These functions will allow the user to walk off the array => Pay attention !
18
Limitations of array
19
2.2. Pointers
20
2.2.1. Pointer variable types
• Roles of pointers:
• Manage dynamic data objects and dynamic storage structures
• to increase speed and flexibility of locating and accessing
21
Declaration
• Declaration: operator *
• T * var;
• Example:
• int *ip; int* ip; int * ip; /* pointer to an integer */
• double *dp; /* pointer to a double */
• char *ch /* pointer to a character, or a string */
• int *pi, j; // pi: pointer to an integer, j: int
• int* pi, j; // pi: pointer to an integer, j: int
• int *pi, *j; // pi, j: pointers to an integer
22
Address operator
char c = ‘A’;
char *pc = &c;
int a[5], *pa;
pa = &a[0];
pa = a;
pa = (int*)pc; // type conversion
23
Indirection/access/dereference operator
• Indirection/access/dereference operator
• access the memory region that the pointer points to
• 3 kind of access operators
• * operator: for char, int, float/double
int a ;
int * pi = &a ;
*pi = 20 ;
24
Indirection/access/dereference operator
(No meaning)
25
Example
• char c = 'A';
int *pInt;
short s = 50;
int a = 10;
pInt = &a;
*pInt = 100;
Address 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
26
Math operations with pointers
• Comparison: 2 pointers of the same type can be compared to each other as two
integers (large, small, equal)
• Two pointers of the same type can be subtracted to get the different number of
elements
27
void * (pure/general pointer)
28
Constant Pointers and Pointers to Constant
29
NULL pointer
30
Pointer to pointer
**ppX = 2.3;
ppX pX x
2.3
31
2.2.2. Pointers vs. arrays
32
2.2.2. Pointers vs. arrays
www.dyclassroom.com
33
2.2.2. Pointers vs. arrays
*(*(zippo+2) + 1) = zippo[2][1]
34
2.2.2. Pointers vs. arrays
• Differences:
• Unable to assign new address to array variable
• Array variables are allocated memory for elements (in the stack)
right from the time of declaration
• The sizeof() operator with arrays indicates the actual size of the
array, while with pointers it gives the size of the pointer itself
• float arr[5]; sizeof(arr) = ?
• float* p = arr; sizeof(p) = ?
• sizeof(arr)/sizeof(arr[0]) ?
• use negative indices with pointer
• int arr[] = {1, 2, 3, 4, 5};
int *p = arr + 2;
p[-1] = 10; /* arr[1] = 10; */
35
2.2.2. Pointers vs. arrays
• Array of pointers
36
2.2.2. Pointers vs. arrays
• Pointers to arrays
• declare a pointer variable pz that can point to a 2D array like zippo?
• int (*pz)[2]; // pz points to an array of 2 ints
• int * pz[2]; // pz is array of 2 pointers of int
[] has a higher precedence than * => need parentheses
37
2.2.2. Pointers vs. arrays
38
Example
39
2.2.3. Dynamic Memory allocation
40
2.2.3. Dynamic Memory allocation
• Memory allocation:
• #include <stdlib.h>
• void *malloc(int size) ;
• size: number of bytes to be allocated, return address of that
allocation
• int *p = (int *)malloc(10*sizeof(int)); /*allocate 10 ints */
• void *calloc(int num_elem, int elem_size) ;
• size = num_elem * elem_size
• void *realloc(void* ptr, int new_size)
• reallocate new size for the memory allocation pointed by ptr
• Allocation may be failed and return NULL need to check
• Free the allocated memory
• void free(void *p);
• free(p);
41
Example
• int *x;
x = (int *)malloc(50 * sizeof(int));
free(x);
• struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp *)calloc(30,sizeof(emp));
• int *x;
x = (int *)malloc(50 * sizeof(int));
x = (int *)realloc(x,100); //allocated a new memory
42
Working with string
• strlen only returns the length of the character string, not counting
'\0'
• Declare pointer does not create memory for pointer to point to
43
Error when using pointer
44
Summary
45
Exercises
46
Exercises
1. Write a program:
• Enter an integer N
• Allocate an array of N integers and input data to it
• Print the array in reverse order
2. Given a one-dimensional array, enter the array data from the keyboard and
sum for all elements of the array.
3. Do exercise 2, but using pointers
4. Write a program to input a string s1, then copy s1 into string s2, using array
5. Write a program to input two strings, s1 and s2, and then compare if they are
the same, using array
6. Write a program to input an array of real numbers without knowing the
number of elements in advance, and also do not enter the number of
elements from the beginning (each time you enter a new number, expand the
array there)
47