Pointers to pointers -


#include <stdio.h> void setupall(int *iptr, int **p, int ***pp, int ****ppp){    *p = iptr;    **pp =iptr;    ***ppp = iptr;    printf("hi\n"); }  int main() {    int = 42, *p, **pp, ***ppp;    setupall(&i, &p, &pp, &ppp);    printf("%u %u %u %u\n", ***ppp, **pp, *p, i); } 

why when run code without ppp, triple pointer, runs prefectly fine , prints 42 3 times. but, when include triple pointer, seg fault within setupall function. in mind, ppp follows same format other 2 pointers i. help?

it crashes because dereferencing pointers before you've initialized them. have same problem if don't have ppp -- got lucky , didn't crash somehow.

what intend following:

#include <stdio.h> void setupall(int *iptr, int **p, int ***pp, int ****ppp){    *p = iptr;    *pp = p;    *ppp = pp;    printf("hi\n"); }  int main() {    int = 42, *p, **pp, ***ppp;    setupall(&i, &p, &pp, &ppp);    printf("%u %u %u %u\n", ***ppp, **pp, *p, i); } 

notice difference in setupall -- dereferencing each pointer once, can set value. rest of "stars" in declaration tell type of thing pointer points to.

edit: elaborate, when **pp, doing *(*pp) -- in other words (a) first find value of *pp pointer int, (b) try find value of int *pp points to. in original code, hadn't initialized *pp yet, pointed somewhere random. @ (b), when try find value of int, can crash if random value returned *pp isn't valid memory address.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -