Arrays and Strings
In questa pagina 5
In C there is a strong relationship between pointers and arrays: any operation done with subscripts can also be done with pointers (the pointer version is generally faster but harder to read). Pointer basics are in Pointers and Dynamic Memorypointers in C: address and dereference operators, pointer arguments, pointers to functions, and dynamic memory allocation with malloc, calloc, realloc and free, with the checks and exercises given in the course.Pointers and Dynamic Memory → (and in Puntatori in CUn puntatore contiene un indirizzo di memoria; operatori & e *, NULL, puntatori come parametri per modificare variabili del chiamante, aritmetica dei puntatori, legame tra array e puntatori, const, puntatori a puntatori.Puntatori in C →).
Arrays and pointers
int a[10]; // 10 consecutive objects a[0], a[1], ..., a[9]
int *pa;
pa = &a[0]; // pa holds the address of a[0]
x = *pa; // copies a[0] into xpa+1points to the next element,pa+ito the element i positions after,pa-ibefore. So*(pa+1)isa[1],pa+iis the address ofa[i],*(pa+i)isa[i].- This holds whatever the type or size of the elements: adding 1 to a pointer means "the next object".
- The value of an array name is the address of element zero, so
pa = &a[0]can be writtenpa = a;. a[i]is converted by C to*(a+i):a[i] == *(a+i),&a[i] == a+i. And with a pointer,pa[i]is*(pa+i).
Array name vs pointer: a pointer is a variable, so pa = a and pa++ are legal; an array name is not a variable, so a = pa and a++ are illegal.
Passing arrays to functions
What is passed is the location of the first element; inside the function the parameter is a local variable holding an address, so the function can treat it as an array or a pointer (both notations allowed).
f(int arr[]) { ... } // equivalent to
f(int *arr) { ... }A part of an array is passed with a pointer to its beginning: f(&a[5]); or f(a+5); pass the subarray starting at a[5]; f does not care that it is part of a larger array. If the elements exist, negative indexes p[-1], p[-2] are legal; going outside the array bounds is not.
Address arithmetic
p++moves to the next element,p += ii elements ahead.- A pointer is initialized like any variable; meaningful values are zero or the address of previously defined data of the right type:
char *pa = a;orchar *pa = &a[0];. - Zero is never a valid address for data, so it signals an abnormal event in functions returning pointers.
NULL(defined in<stdio.h>) is the mnemonic for it. Zero is the only integer that can be assigned to or compared with a pointer. - Comparisons (
==,!=,<,>=...) between pointers to the same array work as expected:p < qifppoints to an earlier element. - Arithmetic or comparisons between pointers into different arrays are undefined; the one exception is the address just past the last element.
pa + nis scaled by the element size (4 bytes for an int: n is multiplied by 4).- If
p < qpoint into the same array,q-p+1is the number of elements fromptoqinclusive.
Simple strlen with pointer subtraction:
/* strlen: return length of string s */
int strlen(char *s) {
char *p = s;
while (*p != '\0')
p++;
return p - s;
}Valid pointer operations: assignment between pointers of the same type; adding or subtracting a pointer and an integer; subtracting or comparing two pointers into the same array; assigning or comparing to zero. Everything else is illegal: adding two pointers, multiplying, dividing, shifting, masking, adding float or double, assigning a pointer of one type to another without a cast (except void *).
Strings and character pointers
A string constant like "I am a string" is an array of characters terminated by '\0': its storage length is one more than the number of characters. Accessing it means using a pointer to its first element: printf("hello, world\n") receives a pointer to the array.
char *pmessage;
pmessage = "I am a string"; // not a copy: only a pointer is assigned
char amessage[] = "I am a string"; // an array
char *pmessage = "I am a string"; // a pointeramessage (array) |
pmessage (pointer) |
|
|---|---|---|
| What it is | array just big enough for the characters and '\0' |
pointer to a string constant |
| Characters | can be modified | modifying them is undefined |
| The name | always refers to the same storage | may be changed to point elsewhere |
Copying strings
s = t copies the pointer, not the characters: a loop is needed. Three versions of strcpy(s, t) from the slides, from explicit to idiomatic:
/* array subscript version */
void strcpy(char *s, char *t) {
int i = 0;
while ((s[i] = t[i]) != '\0')
i++;
}
/* pointer version: arguments are passed by value, so s and t can be moved */
void strcpy(char *s, char *t) {
while ((*s = *t) != '\0') {
s++;
t++;
}
}
/* the way it would really be written */
void strcpy(char *s, char *t) {
while (*s++ = *t++)
;
}Array initialization
int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };- Without explicit size, the compiler counts the initializers (12 here).
- With fewer initializers than the size, the rest is zero (external, static and automatic variables); too many initializers is an error.
- Character arrays: a string can replace the braces notation.
char pattern[] = "hello";equalschar pattern[] = {'h','e','l','l','o','\0'};, size 6.
Multi-dimensional arrays
C has rectangular multi-dimensional arrays, but they are less used than arrays of pointers. A 2D array is a one-dimensional array whose elements are arrays; subscripts are written vector[i][j] (row, column), not vector[i,j]. Elements are stored by rows: the rightmost subscript varies fastest in storage order. Each row is initialized by a sub-list:
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};Passing a 2D array: the parameter must include the number of columns; the number of rows is irrelevant (a pointer to an array of rows, each an array of 13 ints). Equivalent declarations:
f(int daytab[2][13]) { ... }
f(int daytab[][13]) { ... }
f(int (*daytab)[13]) { ... } // pointer to an array of 13 intsThe parentheses are needed because [] binds tighter than *: int *daytab[13] is an array of 13 pointers to int. Only the first dimension is free, all the others must be specified.
Arrays of pointers
Pointers are variables, so they can be stored in arrays. An array of pointers is initialized with a list; the characters of the i-th string are placed somewhere and a pointer to them is stored in element i. If the size is omitted, the compiler counts the initializers.
/* month_name: name of n-th month */
static char *month_name[] = {
"Illegal month", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};2D array vs array of pointers
int a[10][20];
int *b[10];a[3][4]andb[3][4]are both legal references to one int.ais a true 2D array: 200 int-sized locations, element found with20 * row + col.ballocates only 10 pointers, not initialized: initialization must be done explicitly (statically or with code).- Advantage of the pointer array: rows can have different lengths (some 2 elements, some 50, some none). Most frequent use: strings of different lengths.
Related: Pointers and Dynamic Memorypointers in C: address and dereference operators, pointer arguments, pointers to functions, and dynamic memory allocation with malloc, calloc, realloc and free, with the checks and exercises given in the course.Pointers and Dynamic Memory →, Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →, Lab Exercises - Loops, Arrays, Structs and IOlab exercises on loops, arrays, strings, structs, enums and file input: the statements from the course slides with their hints, plus the one solution the slides give (string reversal with an exchange function).Lab Exercises - Loops, Arrays, Structs and IO →, Miscellaneous Syntax - Enums, Typedef, Preprocessor and Morescope and linkage of variables, extern and header files, storage classes (auto, static, register), const and volatile, enumerations, block structure, initialization, the C preprocessor with macros and conditional compilation, and recursion.Miscellaneous Syntax - Enums, Typedef, Preprocessor and More →.
Versione ripasso
a[i] == *(a+i),&a[i] == a+i,pa[i] == *(pa+i);pa = ameanspa = &a[0].pa+nis scaled by the element size.- Array name is not a variable:
a = pa,a++illegal;pa = a,pa++legal. - An array parameter is really a pointer:
int arr[]andint *arrare the same; pass a subarray withf(&a[5])orf(a+5). - Valid pointer operations: same-type assignment, pointer plus/minus int, subtract/compare pointers of the same array, assign/compare with 0 (
NULL). Adding two pointers or arithmetic on different arrays is illegal or undefined. q - pgives the number of elements between two pointers of the same array:strlenisp - s.- String constant =
chararray ending in'\0'(length + 1).char amessage[] = "..."is a modifiable array;char *pmessage = "..."points to a constant: do not modify it. s = tcopies only the pointer; copy characters with a loop:while (*s++ = *t++) ;.- Initialization: size may be omitted (counted by the compiler); fewer initializers leave zeros; too many is an error;
char p[] = "hello"has size 6. - 2D arrays:
a[i][j], stored by rows; a function parameter needs all dimensions except the first:int daytab[][13]orint (*daytab)[13].int *daytab[13]is an array of pointers. int a[10][20]reserves 200 ints;int *b[10]only 10 uninitialized pointers, but rows may have different lengths (typical: array of strings,static char *month_name[] = {...}).- Typical errors: indexing outside the array, modifying a string constant, forgetting the column size in a parameter, forgetting
'\0'.