#include #include /** * Making a passing arrays in a lot of ways. Some of which actually work. * Author: Gtowell * Created: Feb 2021 * **/ /* * OK to pass the array in, but loses the length of the array * @param: farr -- an int array */ void funcc(int farr[]) { printf("BBB %d %d\n", sizeof(farr), sizeof(farr[0])); } /** * The preferred way to passing an array. In this, the link between * the integer passed as the size of the array, and the size of the * array is explicit * arrSize -- the number of items in the array * * farr the array * **/ void funcc2(int arrSize, int farr[arrSize]) { printf("CCC %d %d\n", sizeof(farr), sizeof(farr[0])); } /** DOes not work * Cannot return an array from a function * **/ /** char[] f3(int n) { char arrInFunc[n]; printf("DDD %d %d\n", sizeof(arrInFunc), sizeof(arrInFunc)); } **/ /** * This version of a function that returns an array at least compiles * But using the array outside of the function results in a seg fault * * @param: n the size of the array to create * @return a pointer to the array * **/ char* f3a(int n) { char arrInFunc[n]; arrInFunc[0] = 'a'; printf("DDD %d %d %c\n", sizeof(arrInFunc), sizeof(arrInFunc), arrInFunc[0]); return (char *)arrInFunc; } /** THIS does not compile * Here we are trying to create a global array then replace/overwrite it with an array * created inside a function * * @param n siz the size fo the array being created * **/ char globalArr[10]; // a global array to be replaced /** void f4(int siz) { char zzz[siz]; printf("EEE %d %d\n", sizeof(zzz), sizeof(zzz)); globalArr = zzz; } **/ double globalDArr[500]; int main(int argc, char const *argv[]) { int j = atoi(argv[1]); int arr[j]; printf("local %d %d %d\n", sizeof(arr), sizeof(arr[0]), sizeof(arr)/sizeof(arr[0])); printf("Global %d %d %d\n", sizeof(globalDArr), sizeof(globalDArr[0]), sizeof(globalDArr)/sizeof(globalDArr[0])); funcc(arr); funcc2(j, arr); char* fffa = f3a(j); printf("A char %c\n", fffa[0]); return 0; }