Wednesday, April 18, 2007

C char array output problem.

The strange characters following the correct ones is caused by the lack of ending character ('\o') for a char array.

solution: strncpy

C code failed to run on SunOS 5.4

#include
struct stu
{
char name[8];
short int num;
short int age;
char addr[4];
}boya[2],boyb[2],*pp,*qq;
main()
{
FILE *fp;
char ch;
int i;
pp=boya;
qq=boyb;
if((fp=fopen("stu_list","wb+"))==NULL)
{
printf("Cannot open file strike any key exit!");
exit(1);
}
printf("\ninput data\n");
for(i=0;i<2;i++,pp++)>name,&pp->num,&amp;amp;pp->age,pp->addr);
pp=boya;
fwrite(pp,sizeof(struct stu),2,fp);
rewind(fp);
fread(qq,sizeof(struct stu),2,fp);
printf("\n\nname\tnumber age addr\n");
for(i=0;i<2;i++,qq++)>name,qq->num,qq->age,qq->addr);
fclose(fp);
}


** test source coed was obtained from internet.

> cc test1.c -o test1
> ./test1

input data
tian 1 2 a
Bus error (core dumped)

> uname -a
SunOS 5.8 Generic_108528-13 sun4u sparc SUNW,Sun-Blade-1000

Howerver, it works on FreeBSD.

What's the problem??