Scoping question in C

Kevin Cozens kcozens-qazKcTl6WRFWk0Htik3J/w at public.gmane.org
Sun Jun 12 15:04:53 UTC 2005


pking123-rieW9WUcm8FFJ04o6PK0Fg at public.gmane.org wrote:

>The following code segfaults under Cygwin:
>---------8<----snip-----------8<-----snip-------
>#include <stdio.h>
>#indlude <stdlib.h>
>
>char *x;
>
>int func ()
>{
>   *x = "something";
>  
>
The above line should read:
x = "something";

x will then be set to the address where the string "something" is 
stored. Using *x says to place the address where the string "something" 
is stored in the address pointed to by (ie. currently held in) the 
variable x. This won't work here since x has not been assigned an 
address prior to the assignment and not surprisingly it seg faults.

>   return (1);
>}
>
>int main () {
>   func();
>   printf ("'%s'\n", x);
>   return (EXIT_SUCCESS);
>}
>  
>
You have also declared func() as returning an integer but you never use 
the return value. If you want to ignore the returned value you should 
use "(void)func();" in main(), or declare func() as "void func()" and 
lose the return statement. It will still work either way and even how 
you have shown it above. Adding the void declaration will just save you 
from an extra warning message or two.

-- 
Cheers!

Kevin.  (http://www.interlog.com/~kcozens/)

Owner of Elecraft K2 #2172        |"What are we going to do today, Borg?"
E-mail:kcozens at interlog dot com|"Same thing we always do, Pinkutus:
Packet:ve3syb at ve3yra.#con.on.ca.na|  Try to assimilate the world!"
#include <disclaimer/favourite>   |              -Pinkutus & the Borg

--
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