CC debugging with gdb two dimensional arrays using
C/C++: • debugging with gdb • two dimensional arrays using pointers
C Trivia (1) int main(){ register int d 1 = 99; int *d 2; d 2=&d 1; printf("%d ", *d 2); return 0; }
C Trivia (2) int main(){ int d[3]={3, 5, 7}; int d 1=0; d 1 = ++d[d 1++] + d 1++ + d[--d 1] + d 1; printf("%d ", d 1); return 0; }
Can we see what we are doing before running the program? • Compile your program with -g option: Yes! • c++ -g c. cpp • Run gdb • gdb. /a. out • Type • • break 30 break 80 • Type run • • run print (long) &(arr[0]) print arr[0] set ptr = arr; print (long) ptr step continue
Static arrays are constant!! When you declare int arr[ 10 ] ; arr is now a constant Constant arr is defined to be the address: & arr[ 0 ] You can't do the following: int arr[ 10 ] ; arr = arr + 1 ; // NO! Can't reassign to arr--it's constant However, you can declare a pointer variable int arr[ 10 ] ; int * ptr ; ptr = arr + 1 ; // This is OK. ptr is a variable.
More pointer arithmetic /*more pointer arithmetic*/ int * ptr = arr ; *(ptr+2)+=1; cout <<"int * ptr = arr; n"; cout <<"*(ptr+2)+=1; n"; cout <<"Can you guess the value of arr[2]? "<<"n"; cin>>line; if ( atoi(line. c_str()) == arr[2]){ cout <<"YES! You guessed right!n arr[2] is equal to *(ptr+2) and its value is "; cout <<*(ptr+2) <<"nn"; } else { cout <<"Nope, sorry, try again, correct answer is: "; cout <<*(ptr+2) <<"nn"; }
Can you print the value of arr 2[0] using ptr? gdb a. out break 30 print (long) arr 2 d print (long) &(arr[0]) print (long) &(arr 2[0]) print (long) arr 2[0] print *(arr+14) arr + 14 is valid, even if the array has only ten elements!!
Can you subtract a pointer from another? gdb a. out break 30 print (long) ptr 2 print (long) (ptr 2 -ptr 1)
Two dimensional arrays int arr 2 d[10][3]; what type is arr 2 d? • int * ? • or int **? Two dimensional arrays are contiguous in memory! arr 2 d[ 0 ] = & arr 2 d[ 0 ] arr 2 d[ 1 ] = & arr 2 d[ 1 ][ 0 ] arr 2 d[ i ] = & arr 2 d[ i ][ 0 ] Now print the address: print (long) &(arr 2 d[0]) Can you guess what’s going to print with print (long) &(arr 2 d[1])
Two dimensional arrays 1. int (*ptr)[ 10 ] ; means ptr is a pointer to an array of 10 integers 2. int * ptr[10] ptr is an array of 10 pointers THEY HAVE DIFFERENT MEANINGS!
Dereferencing causes problems You can make a pointer point anywhere. int * ptr= arr + 1000 is valid But… if you access an invalid address, you get a core dump: cout << *(ptr) <<“n”; You can write down anyone's address on a piece of paper! But you can't just go inside the person's house at that address (if you don’t have the key!)
C Trivia (3) int main(){ int d[][3][2]={4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; int i=-1; int j; j=d[i++][++i]; printf("%d", j); return 0; }
- Slides: 12