Declaring Arrays Declare an array of 10 elements
![Declaring Arrays • Declare an array of 10 elements: int nums[10]; • Best practice: Declaring Arrays • Declare an array of 10 elements: int nums[10]; • Best practice:](https://slidetodoc.com/presentation_image/562c9665c3c724f86091e3a1636b58e4/image-1.jpg)



![Examples with functions Declaration void foo (const int nums[] , int s) { int Examples with functions Declaration void foo (const int nums[] , int s) { int](https://slidetodoc.com/presentation_image/562c9665c3c724f86091e3a1636b58e4/image-5.jpg)







- Slides: 12
Declaring Arrays • Declare an array of 10 elements: int nums[10]; • Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; • C 99: int nums[some. Variable] • Declare an array with an initializer list int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Note: Don't need a number between [ and ] • Access elements like primitive variables printf ("%dn", nums[i]); • Declare in a function: void foo(int nums[]) or void foo(int *nums)
Pointer arithmetic Address Content Nums 1000 10 1004 20 1008 22 1012 33 1016 50 1020 66 x 2 int i, nums[6]; for (i=0; i<6; i++) nums[i] = i*10; int *np = nums; *(np+3) = 33; nums[5] = 66; *(&np[2]) = 22; int x = &(np[2]) - &(np[0]) Note: *(nums + 1) is not equal to *nums + 1
Accessing Arrays using pointers An array is just a pointer to a contiguous block of memory • Declaring in a function: void foo(char *data) • Accessing the 10 th element printf("%cn", *(data + 9)); • Another way char *ptr = data+9; printf("%cn", *ptr); • Declare: int *x; – Be careful, there is no memory allocated – C does no memory bound checks
Notes on Pointers • C Programmers often favor pointers to process arrays (less typing) • You can use all the relational operators with pointers (<, >, ==, etc. ) • You can use all the arithmetic operations (++, +=, --, etc. ) • The size in bytes of pointers can be obtained using the sizeof operator
Examples with functions Declaration void foo (const int nums[] , int s) { int i=0, sum=0; for (i=0; i<s; i++) sum += nums[i]; printf("%dn", sum); } Call int nums[] = {1, 2, 3}; foo(nums, 3); Declaration void foo(const int *nums , int s) { int sum=0, *ptr; for(ptr=nums; ptr-nums<s; ptr++) sum += *ptr; printf("%dn", sum); } Call int nums[] = {1, 2, 3}; foo(nums, 3); Note: The const modifier is not required, some arrays can be changed
Strings • In C – – A string is an array of characters (C has no String type) The entire array may not be filled Unlike Java, strings are mutable The string is terminated by a null ('