Что ваш код делает / пытается / не может сделать (см. Добавленные комментарии):
int main(int argc, char** argv)
{
int a = -1; // define and init an int variable, fine
int *b = NULL; // define and init a pointer to int, albeit to NULL, ...
// ... not immediatly a problem
setint(&a, 10); // give the address of variable to your function, fine
cout << a << endl; // output, fine
setint(b, 20); // give the NULL pointer to the function,
// which attempts to dereference it, segfault
cout << b << endl;
Что может достичь того, что вы намерены (по крайней мере, оно достигает того, чего, я думаю, вы хотите ...):
int main(int argc, char** argv)
{
int a = -1;
int *b = &a; // changed to init with address of existing variable
setint(&a, 10);
cout << a << endl;
setint(b, 20); // now gives dereferencable address of existing variable
cout << *b << endl; // output what is pointed to by the non-NULL pointer
Кстати, если вы потом выведите a
снова, он покажет значение, установленное для него через указатель, то есть 20, что переписало ранее записанное значение 10.