What is wrong in this code?

I am not able to access b[i] in the for loop .



char b[30]= " initialize";



if(S==1)

b[] = "SN 2 X 0.001\r MN 2 X 1\r";

else if( S==2)

b[] = "SN 2 X 0.005\r MN 2 X 1\r";

else if(S==3)

b[] = "SN 2 X 0.01\r MN 2 X 1\r";

else if(S==4)

b[] = "SN 2 X 0.02\r MN 2 X 1\r";

else if(S==5)

b[] = "SN 2 X 0.05\r MN 2 X 1\r";

else if(S==6)

b[] = "SN 2 X 0.1\r MN 2 X 1\r";

else if(S==7)

b[] = "SN 2 X 0.2\r MN 2 X 1\r";

else if(S==8)

b[] = "SN 2 X 0.5\r MN 2 X 1\r";

else if(S==9)

b[] = "SN 2 X 1\r MN 2 X 1\r";

else

b[] = "SN 2 X 5\r MN 2 X 1\r";




for( int i=0; i< 40 ;i++)

{

char a = b[i];

xplus0.WriteByte(a);

if ( a == '\0')

break;

}
If you want a string, use a string. That's what strings are for.

So start with:
1
2
3
4
string b = "initialize";
//...
if (S == 0)
    b = "SN 2 X 0.001\r MN 2 X 1\r";
for static data you can avoid construction costs...here b can be loaded straight into memory.

1
2
3
4
5
6
7
8
char *b[] = {"abc", "def", "ghi", "jkl" };

int main()
{
	int S = 2;
	for (int i = 0; i < 3; i++)
             putchar(b[S][i]);
}
@choisum: at the cost of coding errors. "const char* b[] = ..." is what you want. Otherwise you may accidentally try "strcpy(b[0], "foo");" and the compiler would let you (though your OS might not).

You don't have this problem with strings.
yup, const is useful here...
but b is not be changed:it is const
thanks for discussion guys
Topic archived. No new replies allowed.