C-Pointers
C-Pointers
Computing Lab
https://www.isical.ac.in/~dfslab
x p ...
n elements
Pointer values
ip1 = ip2 - n ip2 = ip1 + n
But:
int a[10] = {...}, *p;
CORRECT INCORRECT
p = a; /* same as p = &(a[0]); */ &p &a
*p = 5; /* same as a[0] = 5; */
p[2] = 6; /* same as a[2] = 6; */ p = a; a = p;
*(a+3) = 7; /* same as a[3] = 7; */ p++; a++;
*p = x a[i] = x
1. String copying
do {
*s = *t;
s++; t++;
} while (*t != '\0');
1. String copying
do {
*s = *t;
s++; t++;
} while (*t != '\0');
do {
*s++ = *t++;
} while (*t != '\0');
1. String copying
do {
*s = *t;
s++; t++;
} while (*t != '\0');
do {
*s++ = *t++;
} while (*t != '\0');
p = "abcdefghijklmnop\n";
printf(p);
p = "abcdefghijklmnop\n";
printf(p);
p = "abcdefghijklmnop\n";
printf(p + 2);
p = "abcdefghijklmnop\n";
printf(p);
p = "abcdefghijklmnop\n";
printf(p + 2);
p = "abcdefghijklmnop\n";
printf(p + i);
OK
int num_elts;
WRONG
Syntax:
#include <stdlib.h>
(type *) malloc(n * sizeof(type))
(type *) calloc(n, sizeof(type))
(type *) realloc(ptr, n * sizeof(type))
malloc, calloc, realloc
free(ptr) return void pointers
/* Initial allocation */
if (NULL == (array = Malloc(capacity, int))) {
perror("out of memory");
exit(1); // instead of exit(0)
}
...
a a[0]
...
a[1]
...
. .
. a[rows-1].
...
Computing Lab (ISI) Pointers 14 / 16
Multi-dimensional arrays: row-major storage
mat
cols
... ... ... ...
temp
rows
..
int ii;
int *temp;
if (NULL == (temp = (int *) malloc(rows*cols*sizeof(int))) ||
NULL == (mat = (int **) malloc(rows * sizeof(int *))))
ERR_MESG("Out of memory");
for (ii = 0; ii < rows; temp += cols, ii++)
mat[ii] = temp;
Redesign your program so that it will run correctly even if the number
of lines in the input text is not known a priori.
Computing Lab (ISI) Pointers 16 / 16