POINTERS

ASSIGNMENT

the & operator is used to retrieve a memory address

dataType variableName = {arbitraryValue};
dataType *ptrName = &variableName;

 * the ptrName will receive the memory address of "variableName" along with the "variableName's" data

USAGE

#include <stdio.h>

int main() {
    int variableName = 2;
    int *ptrName = &variableName;                   // Declare a pointer to an integer and assign the address of 'variableName'

    printf("Memory Address: %p\n", (void*)ptrName); // Print the memory address stored in 'ptrName' (which currently holds the address of 'variableName')

    return 0;
}

 * the output is the memory address of 'variableName'
 * Standardization: The %p format specifier in printf is designed to work with void*. While some compilers might be lenient, the C standard recommends casting to void* for consistency and portability.

DEREFERENCING

this means accessing the value stored at the memory location pointed to by a pointer

dataType variableName = {arbitraryValue};
dataType *ptrName = &variableName;

 * ptrName will receive the memory address of "variableName" along with the "variableName's" data


printf("%d", *ptrName);

USAGE

#include <stdio.h>

int main() {
    int variableName = 2;
    int *ptrName = &variableName;    // Declare a pointer to an integer and assign the address of 'variableName'

    printf("Value: %d\n", *ptrName); // Print the VALUE at the memory address pointed to by 'ptrName' 

    return 0;
}

 * The output is the value (2) stored at the memory location where 'variableName' resides. 

Last updated