By Hector M Lugo-Cordero September 17, 2008 Arrays and Pointers By Hector M Lugo-Cordero September 17, 2008 Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Outline Static arrays Pointers Dynamic Arrays The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Static Arrays int data[] = {1, 2, -4, -2, 5}; string test[4]; test[0] = “Bob”; test[1] = “Apu”; test[2] = “Ada”; test[3] = “Isa”; char abc[] = {‘a’, ‘b’, ‘c’}; Indexes go from 0 to N – 1; where N is the length (number of elements) of the array. The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Static Arrays (cont.) for(int i = 0; i < sizeof(data)/sizeof(int); ++i){ cout << data[i] << endl; } sizeof(x): returns the number of bytes that x occupies in memory. The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Pointers Variables that store the reference (memory address) of a value. Memory management functions are in cstdlib. malloc calloc realloc free NULL Unary Operators * & Can be the memory address or to modify a parameter a function The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Pointers (cont.) Other ways of using pointers int* pData = &data; cout << pData << endl; //displays where data is stored cout << *pData << endl; //displays what is inside of data pData = &data *pData = data ++pData: moves the pointer to the next memory position. The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Dynamic Arrays Dynamic arrays change size at running time in contrast to static ones that stay with fix size. Arrays and pointers are the same. int* pData = (int*)calloc(3, sizeof(int)); int pData[3]; int* pData = new int[3]; Dynamic allocation pData = (int*)realloc(pData, sizeof(pData)/sizeof(int)); //WHAT HAPPENS IF YOU DON’T DO THIS???? Another way of writing strings char* mystring = (char*)malloc(10) A char is of size 1 byte The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Questions? ? The Department of Electrical and Computer Engineering