Scoping question in C

pking123-rieW9WUcm8FFJ04o6PK0Fg at public.gmane.org pking123-rieW9WUcm8FFJ04o6PK0Fg at public.gmane.org
Sun Jun 12 13:16:01 UTC 2005


> On Thu, 9 Jun 2005 pking123-rieW9WUcm8FFJ04o6PK0Fg at public.gmane.org wrote:
> > You can test this out yourself with this code, defining a main() and
> > printf'ing the result. On Cygwin, I get nothing (2 carriage
> > returns).
> 
> Show us your code, please -- all of it.
> 

The following code segfaults under Cygwin:
---------8<----snip-----------8<-----snip-------
#include <stdio.h>
#indlude <stdlib.h>

char *x;

int func ()
{
   *x = "something";
   return (1);
}

int main () {
   func();
   printf ("'%s'\n", x);
   return (EXIT_SUCCESS);
}
---------8<----snip-----------8<-----snip-------

I had to change "char *x;" to something like "char x[2] for it to do 
anything. So, this is what I did:

#include <stdio.h>

char x[2];

int func ()
{
   *x = "something";
   return (1);
}

int main () {
   func();
   printf ("'%s'\n", x);
   return (0);
}

This gave it the output:

''

When I compiled your source code with a slight modification: single 
quotes around the %s as in:

printf ("'%s'\n);

I got

'something
'

Note the \n came *before* the closing quote in the output but not in 
the printf().

Paul

> The construct being asked about is legitimate standard C and *will*
> work on any conforming implementation.  I speak as someone who
> participated in developing both versions (C89 and C99) of the C
> standard, and a member of the Standards Council of Canada working
> group that sorts out how Canada should vote at ISO on new C-standards
> issues. 
> 
> Not only will it work on any conforming implementation, it'll even
> work on GCC. :-)  I tried it; it works.  What I wrote was: 
> 
> #include <stdio.h>
> 
> char *x;
> 
> int
> func()
> {
>  x = "something";
>  return (1);
> }
> 
> main() {
>  func();
>  printf("%s\n", x);
>  exit(0);
> }
> 
> It prints "something" in all of the C implementations I've got handy.
> 
>                                    Henry Spencer
>                                    henry-lqW1N6Cllo0sV2N9l4h3zg at public.gmane.org
> 
> --
> The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
> TLUG requests: Linux topics, No HTML, wrap text below 80 columns
> How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml
> 
> __________ NOD32 1.1135 (20050609) Information __________
> 
> This message was checked by NOD32 antivirus system.
> http://www.nod32.com
> 
> 


--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list