3-buggy * array initializaztion is possible: int numbers[5] = {1, 3, 4, 7, 4}; * initialization is distinct from assignment * you can't say numbers = {2,2,2,2,2}; later in the program * there is no array assignment * never return a pointer to stack allocated memory * The compiler may (only) warn you if you do, but it's an error * You code will run correctly "most of the time" nonetheless, which is terrible (because it makes detecting the error through testing hard) 4-copyarray * if callee can't return stack allocated memory, how can the callee "return an array"? * one way is to have the caller allocate the memory for the result and pass a pointer to it to the callee * Caller: int numcopy[5]; copyarray(numbers, numcopy, 5); [note that the array name, numcopy, is a pointer] * Callee: dst[i] = src[i]; [note that dst[i] is equivalent to *(dst+i), so the callee is following the pointer to write results] * an alternative is for the callee to malloc space and pass a pointer back to the caller * who eventually frees that memory? * we'll look at malloc next time 5-arrays-pointers * what are the operations on pointers? * -- dereference (follow the pointer) p+n -- where n is an int the pointer that is n elements past p (if p is an int *, the pointer that is 4*n greater than p; if p is a char *, the pointer that is n greater than p) p-n -- where n is an int just like addition, except subtraction p-q -- where q is a pointer of the same type as p The number of elements between p and q. If p and q are int *'s, for instance, and p is pointing 8 bytes higher in memory than q (and int's are 4 bytes), p-q is 2. [] is a pointer operator p[n] is equivalent to *(p+n) It doesn't matter at all if p was declared as if it were an array (e.g., int p[5]) or not (e.g., int *p;); just evaluate the address of the nth element as though p is pointing at an array and go there. * "aliases" -- two different variables that refer to the same value * pointers provide a way to create aliases * e.g., int x = 2; int *p = &x; * aliases can make things difficult (for the programmer and the compiler) * Does this work? void copyElements( int src[], int dst[], int count) { for (int i=0; i defines a type with name 'struct Point' * Can you assign the value of one struct variable to another? Yes * This means you can return a struct that is allocated on the callee's stack * C is "return-by-value" so the value of the returned struct is copied up to the caller, even though the callee's struct is about to be freed 8-typedef * typedef existing_type new_type_name tells the compiler that new_type_name may be used wherever a type name is proper, and that it means existing_type 9-type equivalence * when are two types the same? Depends on the language... * There are two general approaches: * structural equiv -- memory layout/types are the same * name equiv -- the type names are the same strings * C uses name equivalence for structs * it uses structural equivalence for everything else