100 likes | 184 Views
Address and Value of Array. int a[10]; declare array of 10 integer data items The address of the first memory cell of the first element is &a[0] or just a The address of the first memory cell of the i-th element is &a[i-1], or a+(i-1)
E N D
Address and Value of Array • int a[10]; declare array of 10 integer data items • The address of the first memory cell of the first element is &a[0] or just a • The address of the first memory cell of the i-th element is &a[i-1], or a+(i-1) • The name a is actually an address reference of the arrayint *addr; addr = a; define a pointer veriable addr and then assign the address of a[] to addr*(addr+2) = 1; /* assign value 1 to the third data item */
Demo on Array Address #include <stdio.h> int main() { int j; int *addr, a[10] = {1, 2, 3, 4}; double b[10] = {1.0, 3.0, 3}; printf("%d\n", a); printf("%d\n", a[1]); printf("%d\n", &a); printf("The address of array elements of a[]: \n"); for (j=0; j<10; j++) { printf("%d\n", &a[j]); } printf("The address of array elements of b[]: \n"); for (j=0; j<10; j++) { printf("%d\n", &b[j]); } printf("Pointer and array\n"); addr = a; printf("%d\n", addr); printf("%d\n", addr+2); *(addr+2) = 1; printf("%d\n", *(addr+2)); }
Array and Function • Array elements as function argumentsprintf(“%d”, a[0]);scanf(“%d”, &a[0]); • Formal array argument void fill_array(int list[], int n, int in_value) { int i; for (i = 0; i < n; ++i) list[i] = in_value; } int y[10]; fill_array(y, 10, 1); /* pass the address of the array */ fill_array(&y[0], 10, 1); To fill all array element of y by 1
Function to Find the Largest Element in an Array Array as input argument Int get_max(const int list[], int n) { int i, cur_large; cur_large = list[0]; for (i = 1; i < n; ++i) if (list[i] > cur_large) cur_large = list[i]; return (cur_large); } Const is
Bubble Sort Function void bubble_sort(int a[]) { int i, j, t; for (j = 0; j< MAX; j++) for (i = 0; i < MAX - 1 -j; i++) if (a[i] > a[i+1]) { t = a[i]; a[i] = a[i+1]; a[i+1] = t; } } #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 50000 void bubble_sort(int a[]); int main(){ int j, a[MAX]; /* clock_t ticks1, ticks2; */ for (j=0; j<MAX; ++j) { a[j] = rand()%100; printf("%d, ", a[j]); } /* ticks1=clock(); */ bubble_sort(a); /* ticks2=clock(); printf("Took %f ticks to wait one second.\n", (double) (ticks2-ticks1)/CLOCKS_PER_SEC); */ printf("\n\nThe sorted sequence is:\n\n"); for (j = 0; j<MAX; ++j) printf("%d, ", a[j]); fflush(stdin); getchar(); return 0; }
Function Using a Sentinel-Controlled Loop to Store Input Data in an Array