Reputation: 89
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)
.
Upvotes: 0
Views: 212
Reputation: 1
The reason why the second set doesn't work is that you are attempting to modify a string literal (char *colour = "foo") which is not allowed in C.
As an aside, both versions have undefined behavior, and you should consider compiling with all of the -W flags on.
Upvotes: 0
Reputation: 7374
To see why the second group of code doesn't work it may be helpful to see it as:
if (i==0) {
char *colour = "RED";
}
if (i==1) {
char *colour = "BLUE";
}
You can see more easily that the declaration of colour
extends only to the end of the block, so that colour
no longer exists when the next statement is executed.
As for your second question, setColor
is only using the value of colour
, (which is already a pointer) so no need to pass a reference to it. setcolor
can access the string without the reference.
Upvotes: 1