Array
1. char array[] = "abc" sets the first four elements in array to 'a', 'b', 'c' and '\0'.
char *ptr = "abc" sets pointer to the address of the "abc" string, which may be stored in read only memory and thus unchangeable.
2. The C standard C99 allows variable length arrays.
int func(int n)
{
float vals[n];
}
3. C treats array parameters as pointers.
void foo(int arr_param[]) { arr_param = NULL;}
void foo(int *arr_param) { arr_param = NULL;}
Array parameters treated as pointers because of efficiency. It is inefficient to copy the array data in terms of both memory and time.
4. Is the expression 5["abcdef"] legal?
Array subscripting is commutative in C.
a[e], *((a) + (e)), *((e) + (a)), e[a] are same.
char *tmpptr = "abcdef";
tmpptr[5], 5["abcdef"], "abcdef"[5] are same.
5. How do I declare a pointer to an array.
int a1[3] = {0,1,2};
int a2[2][3] = {{3,4,5}, {6,7,8}};
int *ip; //pointer to int
int (*ap) [3] //pointer to array [3] of int
ip = a1;
printf("%d", *ip); //0
ap = &a1;
printf("%d", **ap); //0
ap++; //Wrong
ap = a2;
printf("%d %d", (*ap)[0], (*ap)[1]); //3 4
ap++;
printf("%d %d", (*ap)[0], (*ap)[1]); //6 7
6. How can I determine how many elements are in an array, when sizeof yields the size in bytes.
Simply divide the size of entire array by the size of one element.
int array[] = {1,2,3};
int narray = sizeof(array) / sizeof(array[0]);
7. Compiler complained on passing two-dimensional array to a function expecting a pointer to a pointer.
An array of arrays decays into a pointer to an array, not a pointer to a pointer.
int array[NROWS][NCOLUMNS];
f(array);
f(int a[][NCOLUMNS]);
f(int (*ap)[NCOLUMNS]);
8. How can I dynamically allocate a multidimensional array?
Method 1: Max call to malloc
int **array1 = (int **)malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
array1[i] = (int *)malloc(ncolumns * sizeof(int));
Method 2: Two call to malloc
int **array2 = (int **)malloc(nrows * sizeof(int *));
array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
for(i = 1; i < nrows; i++)
array2[i] = array2[0] + i * ncloumns;
Method 3: One call to malloc
int **array3 = (int **)malloc(nrows * sizeof(int *) + nrows * ncolumns * sizeof(int));
for(i = 0; i < nrows; i++)
array3[i] = array3[nrows] + i * ncolumns;