help me with this c code?

Status
Not open for further replies.

welove8051

Full Member level 6
Joined
Jul 16, 2009
Messages
357
Helped
51
Reputation
102
Reaction score
41
Trophy points
1,308
Location
india
Activity points
3,277
Code:
#include <HTC.H>

__CONFIG(XT & WDTDIS & PWRTDIS & BORDIS & LVPDIS & WRTEN );

unsigned char a,b,i,seg[11]={192,249,164,176,153,146,130,248,128,144,127};
void init()
{
	TRISB=0;
	PORTB=128;
	i=0;
	

}


void main()

{
	init();
	
	while(1)
	{
	for(i=0;seg[i]!='\0';i++)
{
	b=seg[i];
	a=~b;
	PORTB=a;
_delay(100000);
_delay(100000);
_delay(100000);
_delay(100000);
_delay(100000);
	
}
while(1);
}
}


this code is used to display 0 to 9 and dot in 7 seg.

my doubt is how we detect a end of array or a string using null character and how to use it in the for loop.

for(i=0;seg!='\0';i++)



regards
kj
 

What he said - or if you need abstraction

for(i=0 ; i < sizeof(seg) ; i++)


jack
 

In some cases, e.g. when using more than one table with different lengths, the terminating null idea isn't bad.
Unlike a string, an array of characters get's no terminator automatically. You have to insert it, and also increase
the array size by one.
Code:
seg[12]={192,249,164,176,153,146,130,248,128,144,127,0};
 

Code:
for(i=0;seg[i]!='\0';i++)

since you know precisely what seg[] is, you know how exactly the above code will go wrong.
 

@jumper2high
i know we can calculate length of string and enter in the for loop, but for large string and different lengths it is a tedious process.


@fvm
can u give me example for using null character in for loop for a string.

@millwood
a long time before i had used this null character concept. but i had forgot how to use it and also where i used it.
 

when you define this:
Code:
seg[11]={192,249,164,176,153,146,130,248,128,144,127};
you define a 11-elements array, with the first eleven (from seg[0] to seg[10]) filled.

so it's jsut luck that it works...

when you define as
Code:
seg[12]={192,249,164,176,153,146,130,248,128,144,127};
the first eleven elements are the same, but most compilers 'fills' the last element with 0 (0x00 or '\0' all means 0)
of course, it's a best practice to put that 0 in the array

Code:
seg[12]={192,249,164,176,153,146,130,248,128,144,127,0}; //best approach

most C compilers 'add' an extra 0 at the end of a string (this is called a null-terminated string)

so

unsigned char h[10]="HELLO";

is the same as:

unsigned char h[10]={'H','E','L','L','O',0};

for strings it's better to search the 0, but for arrays (like your case, where you know the size of the array) it's better to use the size as limit (as @jumper2high said)
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…