A function can not change the values of its own argument variables.
If you want a function to change its own argument variables, use pointers as arguments, to refer to the variables indirectly
swap(int a, int b); // can not change the values of integers a and b
swap(int *a, int *b); // can change variables a and b, since they aren't referred to directly.
When an array is used as an argument of a function, the first element of the array (array[0]) is being referred to in the function.
Function parameters are just already declared local variables
Current array size (how many elements are in the array?)
Current array capacity (how many elements can fit in the array’s allocated memory?)
A pointer to the elements of the array. This is generated with malloc/calloc
// Defining the dynamic array
typedef struct {
int *elements; // Pointer to elements of the array
int size; // Tracks current size
int cap; // Tracks allocated memory size
} dynamic_array;
// Generating a dynamic array
dynamic_array a1;
// Initializing dynamic array a1
arr.size = 0; // No elements at first.
arr.elements = calloc(1, sizeof(arr.elements) ); // Dynamically allocated memory for array
arr.cap = 1; // Array can hold 1 element
// Expanding the array (increasing capacity) is done using realloc
arr.elements = realloc(arr.elements, (5 + arr.cap) * sizeof(arr.elements));
if (arr.elements != NULL)
arr.cap += 5; /* increase capacity */
// Increases array size if an element is added
if (arr.size < arr.cap) {
arr.elements[arr.size] = 50;
arr.size++;
} else {
printf("Need to expand the array.");
}
void *ptr
Can be used to point to any data type
If you use a void pointer, you must dereference it like this:
Add type casting with a pointer of the data type it points to. If it points to a char → (char *)
Make sure you have parenthesis around the whole thing.
*((float *)ptr) // works
*ptr // doesn't work
You can’t do pointer arithmetic with void pointers.
Use void pointers in function declarations to allow any return type to be used.
void* MultiplyBy2 (const void *num) { // Declaration using void pointer
int result;
result = (*(int *)num) * 2; // Type casting to make the result an int
return result;
}