25_pdfsam_cs2022

# 25_pdfsam_cs2022 - int main(void int A[5 ={3 7-1 4 6 int j...

This preview shows pages 1–6. Sign up to view the full content.

Arrays Arrays in C are zero based. e.g., A[0], A[1], A[2], A[3], A[4]. Example int main(void) { int A[5] = {3, 7, -1, 4, 6}; int j; double mean = 0; // compute mean of values in A for(j=0; j<5; j++) mean += A[j]; mean /= 5; return 0; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Arrays and pointers Pointers and arrays are closely related An array variable is actually just a pointer to the first element in the arrays You can access array elements using array notation or pointers A[0] is the same as *A A[1] same as *(A+1), A[2] same as *(A+2) etc. ... // create an array with 5 integer elements int A[5] = {3, 7, -1, 4, 6}; 300 3 303 302 301 303 304 305 306 307 7 -1 4 6 A A[0] A[2] A[1] A[3] A[4]
Arrays and pointers Accessing array elements using pointers:

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int main(void) { int A[5] = {3, 7, -1, 4, 6}; int j; double mean = 0; // compute mean of values in A for(j=0; j<5; j++) mean += *(A+j); mean /= 5; return 0; } Some examples Q: How to access the integer at index 0 of A? A: A[0] or *A Q: How to access the integer at index 3 of A? A: A[3] or *(A+3) Q: What is the address of the first element of A? A: A or &(A[0]) Q: What is the address of the 2nd element of A? A: A+1 or &(A[1]) // create an array with 10 integer elements int A[5] = {3, 7, -1, 4, 6}; Bounds checking What happens when you run this code? int A[5] = {3, 7, -1, 4, 6}; A[28] = 5; A[-3] = 12;...
View Full Document

{[ snackBarMessage ]}

### Page1 / 6

25_pdfsam_cs2022 - int main(void int A[5 ={3 7-1 4 6 int j...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online