mixing pointers and arrays

Mark Plotnick mp at mit-eddie.UUCP
Mon Aug 1 08:16:21 AEST 1983


ihuxa!dixon recommended the following:

    If you wanted to print a string of characters using a pointer to that
    string, then you should use

      printf("%s\n",yytext);           rather than

      printf("%s\n",*yytext);

    since yytext has been declared to be a pointer to a character string.

Well, this is almost right.  Since the loader (at least on 4.1bsd and
System 3) has deemed that the external symbol _yytext is equal to
something like 10600 (the start of the 10-element array), if you do
printf("%s", yytext), you're going to get either a segmentation fault or
a lot of garbage, since you're passing printf the contents of 4 bytes
starting at 10600, which is 16230262571 on our machine.  If you do
printf("%s", *yytext), you'll have an even better chance of core
dumping.

The solution is to use compatible declarations - in this case, yytext
should be declared as
	extern char yytext[];
in the first program, not
	extern char *yytext;
THEN you can use dixon's suggested fix.

The System V loader presumably catches conflicting declarations such as
this, and may even catch such favorite constructs as multiple external
definitions.  The 3B20 loader of several years ago caught these errors
and I had a wonderful time while porting some Berkeley software in which
every module #included a header file full of global definitions.

	Mark (genrad!mit-eddie!mp, eagle!mit-vax!mp)



More information about the Comp.lang.c mailing list