I'm trying to understand how passing pointers to functions work, but I don't understand the following situation : Why this code work
void setVar(uint32_t* var) {
*var = 10;
}
int main() {
uint32_t myVar = 0;
setVar(&myVar);
return 0;
}
and this one lead to a runtime error ? :
void setVar(uint32_t* var) {
*var = 10;
}
int main() {
uint32_t* myVar = 0;
setVar(myVar);
return 0;
}
I'd appreciate your answers.
The issue is not the pointer.
The issue is that you initialize the pointer you pass to the function with 0 (uint32_t* myVar = 0;
) and then dereference it in your function (*var = 10;
), which is disallowed.
You should make sure, the pointer that is passed is not a NULL
pointer, either do that within the function or make sure that function only ever is called with valid parameters.