80 likes | 97 Views
This session provides a review of C programming and PostgreSQL basics, with a focus on pointers, arrays, and strings. It also highlights common pitfalls and how to avoid them. Learn how to survive C programming and enhance your PostgreSQL skills.
E N D
Surviving C and PostgreSQL CS186 Supplemental Session 9/13/04 Matt Denny, Paul Huang, Murali Rangan (Originally prepared by Shariq Rizvi, Wei Xu, Shawn Jeffery)
Outline • A Review of C • PostgreSQL Basics • Tour of Assignment 1 • 2Q
A Review of C • Review Pitfalls of C Programming for Java Programmers • Pointers and Arrays • Strings • Segmentation Faults • For more information, consult “ The C Programming Language” by Kernighan and Ritchie or tutorial on web site
any float f f_addr ? ? ? any address 4300 4304 f f_addr ? 4300 4300 4304 • Pointer = variable containing address of another variable • float f; /* data variable */ • float *f_addr; /* pointer variable */ • f_addr = &f; /* & = address operator */
f f_addr 3.2 1.3 4300 4300 4300 4304 f f_addr 4300 4304 *f_addr = 3.2; /* indirection operator */ float g=*f_addr; /* indirection:g is now 3.2 */ f = 1.3;
Arrays and Pointers int month[12]; /* month is a pointer to base address 430: system allocates 12*sizeof(int) bytes at 430 */ month[3] = 7; /* integer at address (430+3*sizeof(int)) is now 7 */ ptr = month + 2; /* ptr points to month[2], i.e. ptr =(430+2 * sizeof(int)) = 438 */ ptr[5] = 12; /* int at address (434+5*sizeof(int)) is now 12; same as month[7] */ • Now , month[6], *(month+6), (month+4)[2], ptr[4], *(ptr+4) are all the same integer variable.
Strings #include <stdio.h> main() { char msg[10]; /* array of 10 chars */ char *p; /* pointer to a char */ char msg2[]=“Hello”; /* msg2 = ‘H’’e’’l’’l’’o’’\0’ */ msg = “Bonjour”; /* ERROR. msg has a const address. Think of space allocation*/ p = “Bonjour”; /* address of “Bonjour” goes into p */ p = msg; /* OK */ p[0] = ‘H’, p[1] = ‘i’,p[2]=‘\0’; /* *p and msg are now “Hi” Warning: be careful if you have space allocated for p!!*/ }
Segmentation Fault? • You reference memory that the OS doesn’t want you to • What to check? • Dereferencing a null pointer 99% • Output or trace with a debugger • Check array bounds