Thursday, August 22, 2019

CS2100: Pointers and referencing

Declaration

- The & operator gives the address of a variable
- The *ptr means that ptr is a pointer variable and anything thats assigned to ptr is a mem location
- Memory is integer
Note: Memory is not always consecutive

Usage

Declaring x:
int x;

Declaring pointer:
int *ptr, *ptr2

Point ptr to x's address:
ptr = &x
//*ptr is pointing to the x, ptr contains the address of x

Copying:
ptr2 = ptr
//ptr2 is copying ptr, it has the mem add of x

Dereferencing

We use the * infront of the pointer to manipulate the destination
ie.

ptr = &x 
// ptr contains the mem add of x and points to x

*ptr = 1234 
//we changed the value of x to 1234

ptr = 1234 // ptr is now pointing at the mem address of 1234 not x

Note: using *ptr = &x is wrong!!

Application

scanf("%lf", &input)
// We assign the value into the address &input

We can also use it through function
e.g:
swap_Add(&i,&j);

void swap_Add(int* a, int* b){
  int temp;
  
  temp = *a;
  *a = *b;
  *b  = temp;
}

<Prev                        Next>

No comments:

Post a Comment