More About Pointers
More About Pointers
Part -1 (disclaimers):
I sometimes leave off “return 0;”. It’s slightly bad form, but C will do it for you.
I don’t write in code for checking if the returned pointer from malloc is null; you should,
but as you said, it’s often not a problem because our computers usually have lots of
memory.
Part 0 (review)
A pointer: Holds the memory address of another variable. In essence, it “points” to that variable,
because that normal variable can be accessed through this pointer.
An example:
int main(){
int a; //This declares a normal int variable (like in Java)
a = 3;
Part 1
#include <stdio.h>
int main(){
int a; // a normal variable (int)
int *p; // a pointer to an int
int **q; // a pointer to a pointer to an int
a = 3;
p = &a; //assigns address location of a to p
q = &p; //assigns address location of p to q
return 0;
}
int main(){
free(array);
//above statement frees the memory, i. e. deletes it
}
But how do we create two-dimensional arrays? Well, first we allocate memory for the initial one-
dimensional array of integer pointers, and then allocate memory for an array for each of those
new pointers. However, freeing this array becomes slightly more complicated as well (you must
free the subarrays first and then the main array, i. e. free memory in the reverse order that you
allocated it).
int main(){
int nrows = 5; //create an array of 5 "rows"
int ncolumns = 5; //and 5 "columns"
Part 2
I actually found out there’s more support for complex numbers than I thought.
#include <stdio.h>
#include <complex.h>
int main(){
complex double z = 2 + 3*I;
complex double a = 4 - 5*I;
complex double d = z/a;
return 0;
}
Important notes:
You must include the header file <complex.h>
Capital I is used to denote the imaginary unit.
creal returns the real part of a complex number, cimag returns the imaginary part
You can also dynamically allocate arrays (one and two-dimensional) of complex numbers.
int main(){
int num_of_elements = 8; //let’s say 8 elements in array
free(complex_array);
int main(){
int nrows = 7; //let’s say 7 rows in array
int ncolumns = 7; //and 7 columns