c - CS50 PSET4 pointers -
i attempting cs50 pset4.
can explain why first works instead of second?
essentially did was, declare char* colour outside loop in first , declared char* color inside of if statements in second.
this worked when declared char* outside of if statements
void initbricks(gwindow window) { char* colour; // todo for(int i=0,y=20;i < rows; i++) { y+= 30; for(int j=0,x=5,c=0;j < cols; j++) { if(i==0) colour = "red"; if(i==1) colour = "blue"; if(i==2) colour = "cyan"; if(i==3) colour ="orange"; if(i==4) colour = "gray"; grect brick = newgrect(x,y,30,15); setfilled(brick,true); setcolor(brick, colour); add(window, brick); x+= 40; } } }
but didn't work, when declared char* inside if statements
void initbricks(gwindow window) { // todo for(int i=0,y=20;i < rows; i++) { y+= 30; for(int j=0,x=5,c=0;j < cols; j++) { if(i==0) char *colour = "red"; if(i==1) char *colour = "blue"; if(i==2) char *colour = "cyan"; if(i==3) char *colour ="orange"; if(i==4) char *colour = "gray"; grect brick = newgrect(x,y,30,15); setfilled(brick,true); setcolor(brick, colour); add(window, brick); x+= 40; } } }
i new pointers far sort of understand char* sort of equivalent of string points address of variable, colour, in case.
however, not sure why don't have put in '&'
(reference operator) when use in setcolor(brick, colour)
.
to see why second group of code doesn't work may helpful see as:
if (i==0) { char *colour = "red"; } if (i==1) { char *colour = "blue"; }
you can see more declaration of colour
extends end of block, colour
no longer exists when next statement executed.
as second question, setcolor
using value of colour
, (which pointer) no need pass reference it. setcolor
can access string without reference.
Comments
Post a Comment