The concept of a pointer was confusing to me when first learning C, here are some questions and info that I think would’ve been helpful to know:
Terms to know
- Memory Address
- Format Specifiers
- Poimter Arithmetic
What are pointers?
- A pointer in C is variable that gets its value from the memory address of another variable.
When are they used?
- To manipulate the computer’s memory
- Working with arrays
- Reduce length of code
- Improve performance
- Implementing data structures
How to use pointers?
A pointer variable is created by assigning a data type and the * (star) operator, the pointer points to a variable of the same data type.
Example:
1
2
int num = 2;
int* numPointer = #
numPointer is a variable that stores the address of num. The & operator references to the variables memery address. Using the * opperator dereferences the pointer and returns value the pointer points too.
More to think about
Working with strings and arrays
- There are no string declaration in C. You actually create a one-dimensional array of characters. Each of the characters can be accessed through their own memory address. Pointers can help manipulate the strings and arrays.
How to change a value of a variable from another function?
Passing a variable as a parameter from on function to another function does not actually pass the variable, it passes a copy of the variable. When the value of the variable is updated in the function the value is not changed in the original function. To change the value, you have to pass a pointer and change what it points to.
Example:
1
2
3
4
5
6
7
8
9
void setChar(char* charToChange) {
*charToChange = 'B';
}
int main() {
char result = 'A';
setChar(&result);
printf("%C", result);
}
Incrementing with pointers
- Pointers holds a memory address, which a numeric value that can be iterated through using the following aritmetic opertors: ++, –, +, -