Pointers and Arrays: ESC101 October 25
Pointers and Arrays: ESC101 October 25
ESC101
October 25th
Announcements
• MQ2 copies shown in tutorial next week
• Lab end sem exam on 11th November in NCL (as
before)
– Syllabus: everything
– Logistics: same as before
• Theory end sem exam on 22nd November afternoon
– Details to follow
– Cannot miss this exam
• End sem copies shown on 27th November
– Vacation begins 28th
Recap: dynamic memory allocation
int * ar;
….
ar = (int *) malloc(…); // allocate memory
if (ar == NULL) { // or if (!ar)
// take corrective measures and return failures
}
…ar[i] …
free(ar); // free after last use of ar
Question
• What is the difference between the arr we get
from
– int arr[10]
– int *arr followed by arr = malloc(sizeof(int)*10)
• Both are pointers to the first block of memory
assigned to the array
• Static assigned pointer cannot be re-assigned
• Dynamically assigned pointer can be re-
assigned
Question: realloc and free
• How do we free a pointer we passed into
realloc and returned out into the same
variable name?
– If realloc succeeds in memory allocation, old
memory is automatically freed
– If realloc fails, it returns the old address as the
new address
Arrays and Pointers
• In C, array names are nothing
int ar[10], *b;
but pointers.
– Can be used interchangeably in ar = ar + 2;
most cases
ar = b;
• However, array names can
not be assigned, but pointer b = ar;
variables can be. b = b + 1;
– Array name is not a variable. It
gets evaluated in C. b = ar + 2;
b++;
Aug-19 6 Esc101, Pointers
Precedence (Unary Refined)
( ) [ ] LR
* (deref) ++ -- ! & +- RL
* / % LR
+ - LR
== != LR
&& LR
|| LR
= RL
, LR
Array of Pointers
• Consider the following declaration
int *arr[10];
• arr is a 10-sized array of pointers to integers
• How can we have equivalent dynamic array?
int **arr;
arr = (int **) malloc ( 10 * sizeof(int *) );
int j;
for (j = 0; j < 10; j++)
arr[j] = (int*) malloc (sizeof(int));
Aug-19 9 Esc101, Pointers
Subtle difference
• Array of pointers • Pointer to array
Solution: Version 1
scanf("%s",st);
len = strlen(st);
nsubstr = len*(len+1)/2;
substrs = (char**)malloc(sizeof(char*) * nsubstr);
for (i=0; i<nsubstr; i++)
substrs[i] = (char*)malloc(sizeof(char) * (len+1));
E ‘\0’
E S ‘\0’
E S C ‘\0’
S ‘\0’
S C ‘\0’
C ‘\0’
Solution: Version 2
len = strlen(st);
nsubstr = len*(len+1)/2;
substrs = (char**)malloc(sizeof(char*) * nsubstr);
Solution: Version 3
scanf("%s",st);
len = strlen(st);
nsubstr = len*(len+1)/2;
substrs = (char**)malloc(sizeof(char*) * nsubstr);