31_pdfsam_cs2022 - Out of bounds error example #include...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
Out of bounds error example #include <stdio.h> int main() { int b = 4; int A[]={1,2,3}; A[7] = 12; printf("%d", A[7]); return 0; } 12
Background image of page 1

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

View Full DocumentRight Arrow Icon
Arrays aren’t necessary! Array syntax is just syntactic sugar It’s never necessary: you can always use pointers instead But often array syntax is easier to read A[B] is translated by the compiler into *(A+B) e.g. A[12] becomes *(A+12) either A or B must be a pointer This allows for some unusual expressions 12[A] is the same as A[12] 12[(int *)100] is the same as *((int *)112) avoid these unusual expressions in practice
Background image of page 2
Passing arrays to functions #include <stdio.h> int change_and_sum( int *a, int size ) { int i, sum = 0; a[0] = 100; for( i = 0; i < size; i++ ) sum += a[i]; return sum; } int main() { int a[5] = { 0, 1, 2, 3, 4 }; printf( "Sum of a: %d\n", change_and_sum( a, 5 )); printf( "Value of a[0]: %d\n", a[0] ); return 0; }
Background image of page 3

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

View Full DocumentRight Arrow Icon
Pointer arithmetic C lets you perform arithmetic on pointers pointer + integer, pointer - integer
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

31_pdfsam_cs2022 - Out of bounds error example #include...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online