Академический Документы
Профессиональный Документы
Культура Документы
Character Values
• There are a fixed number of char values
1
A char Variable
Pointer Values
There are a fixed number of pointer values
2
Pointer Values(Constants)
3
Printing Pointers
Address of the
first byte of
the variable
4
Pointer Variables
Possible to define variables holding pointers
Pointer Variables:
– Contain a pointer constant (i.e., an address)
– Can have value changed
– “Point” to a specific type of data
– Many variables can point to the same value!
Pointer Variables
5
Schematic : Pointer Variables
6
Examples : Get them right !!
Examples:
char *p;
int *q;
float *r;
long double *s;
long long int *t;
7
Uninitialized Pointers
As with all variables in C:
If you don’t initialize you get
whatever junk is found at that time !!!
BEWARE:
Uninitialized pointers contain some address
Uninitialized Pointers
8
Initializing : Be safe - to nowhere
What if a pointer variable shouldn’t point anywhere?
Initialization to Somewhere
int a;
int *p;
p = &a;
Remember :
• Never try to dereference a NULL pointer
• Gives run-time error (a segmentation fault ??)
9
Example : Add using pointers
Pointers as Parameters
C uses pass by value!!
10
Returning Pointer Variables
Suppose we want to return a pointer?
Example:
int *smaller (int *p1, int *p2);
It returns a pointer to an integer...
11
Returning Pointer Variables
float *mistake() {
float temp = 12;
return &temp;
}
Points to space on stack that isn’t used !!
12
Pointers to pointers
If a pointer variable “points” somewhere:
Why not to another pointer variable??
int **p;
This variable pointer to a pointer which points to an integer...
Pointers
to
Pointers
13
Using Pointer to Pointers…
14
Sizes and Compatibility
char c;
char *pc;
int a;
int *pa;
double x;
double *px;
Print
sizeof(c), sizeof(pc), sizeof(*pc)…
15
Types
&
Validity
16
Using Expressions
Expressions evaluate to a value
17
The 7 lvalues
(Blue not covered yet)
Expression Type Comments
1 Identifier x Variable identifier
2 Identifier[] A[i] Array indexing
3 (expression) (A+7) Expression must be lvalue
4 *expression *(A+7) Dereference expression
5 expression.name Structure selection
6 expression->name Structure indirect selection
7 function call If returning an address
lvalue expressions
a = …
a[5] = …
(a) = …
*p = …
18
Some Operators Require lvalues
Anything that can be changed
Mistakes
The following are rvalue expressions where
there should be an lvalue.
Expression Problem
a+2 = 6; a+2 is an rvalue can’t be modified
&(a+2); a+2 is rvalue address requires lvalue
&4; Same as above
(a+2)++; Postfix inc. needs an lvalue
++(4-b); Prefix inc. needs an lvalue
19
Returning multiple values
Definition:
/*The function may return an error code */
int SecondsToHours(long time, int *hours,
int *minutes, int *secs) {
/* what is this code? */
….
*hours = time/3600 ;
….
}
Returns a value 1 if the computation fails
Calling code:
SecondsToHours(totalTime,&hrs,&min,&s);
20