The following C code returns a \"segmentation fault\" error. I do not understand why it does not return the value 20. What is my error?
#include
You are trying to write 20
in garbage value. You must allocate space for it by using one of *alloc()
functions or creating an int on stack and getting the andress of it(as Richard J. Ross III mentioned on comments).
dynamic allocation:
int n*;
n = malloc(sizeof(int)); /* allocate space for an int */
if(n != NULL) {
/* do something.. */
free(n); /* free 'n' */
} else {
/*No space available. */
}
or on the stack:
int int_on_stack;
int *n = &int_on_stack;
*n = 20;
printf("%i\n", *n); // 20