I am attempting CS50 PSET4.
Can someone explain why the first works instead of the second?
Essentially what I did was, I declare char* colour outside the loop in the first and declared char* color inside all of my if statements in the second.
This worked when I declared char* outside of the 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 this didn't work, when I declared char* inside all the 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 am fairly new to pointers but so far I sort of understand that char* is sort of the equivalent of a string where it points to the address of the variable, colour, in this case.
However, I am not sure why I don't have to put in the '&'
(reference operator) when I use it in setColor(brick, colour)
.
To see why the second group of code doesn't work it may be helpful to see it as:
You can see more easily that the declaration of
colour
extends only to the end of the block, so thatcolour
no longer exists when the next statement is executed.As for your second question,
setColor
is only using the value ofcolour
, (which is already a pointer) so no need to pass a reference to it.setcolor
can access the string without the reference.