Unit 5
Unit 5
•Syntax: &variable_name
int num = 50;
int *p;
p = # // p now stores the address of num
printf("%p", p); // prints the address of num
Declaration syntax:
•datatype *pointer_name;
•Eg:
int *p;
char *c;
Initialization: Assign a pointer to the address of an
existing variable.
int a = 20;
int *p = &a; // pointer p points to the address of a
Accessing a Variable through its Pointer
Syntax:
datatype **pointer_name;
int a = 10;
int *p = &a; // pointer to int
int **pp = &p; // pointer to pointer to int
printf("%d", **pp); // prints the value of a (10)
Pointer Expressions
•Example:
int a[3] = {1, 2, 3};
int *p = a;
p++; // moves to the next integer (p += sizeof(int))
•If p points to an integer, incrementing it increases
its value by the size of int (typically 4 bytes).
return_type (*function_pointer)(parameters);
int add(int a, int b) {
return a + b;
}
int main() {
int (*func_ptr)(int, int) = &add;
printf("%d", func_ptr(2, 3)); // calls the add function, prints 5
}
Pointers and Structures
fclose(fp);
•fgetc(), fputc(): Reads and writes a character to/from a
file.