C Pointers & Functions
In this page:
Call by Value
This is C's default parameter-passing behavior for all non-array, non-pointer types -- it protects the caller's data but means the function has no way to report a result back except through its return value, which limits it to a single output.
Example: Call by Value
#include <stdio.h>
void tryChange(int x) {
x = 100;
}
int main() {
int value = 5;
tryChange(value);
printf("%d", value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Call by Reference
This is the standard technique C uses to simulate 'output parameters,' since a function can only truly return one value -- functions like scanf() rely entirely on this pattern, which is why you write scanf("%d", &x) with the address-of operator.
Example: Call by Reference
#include <stdio.h>
void change(int *x) {
*x = 100;
}
int main() {
int value = 5;
change(&value);
printf("%d", value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Swapping Two Numbers
A classic teaching example that demonstrates why call by value alone can't swap two variables: the function must receive pointers to both variables so it can dereference and exchange their actual stored values, not just local copies.
Example: Swapping Two Numbers
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("%d %d", x, y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Returning Pointers from Functions
This is a genuinely dangerous pattern to avoid -- a local variable's memory is reused as soon as the function returns, so a pointer to it becomes a 'dangling pointer' pointing at invalid, potentially overwritten memory.
Example: Returning Pointers from Functions
#include <stdio.h>
int* getStatic() {
static int value = 42;
return &value;
}
int main() {
int *ptr = getStatic();
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Passing Pointer Arrays
Passing an array of pointers (like char *names[]) lets a single function operate on a whole collection of separately-allocated strings or structures without needing to know their individual sizes in advance -- this is exactly how argv works in main().
Example: Passing Pointer Arrays
#include <stdio.h>
void printNames(char *names[], int count) {
for (int i = 0; i < count; i++) {
printf("%s ", names[i]);
}
}
int main() {
char *names[2] = {"Ann", "Bob"};
printNames(names, 2);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: