Scoping question in C
Henry Spencer
henry-lqW1N6Cllo0sV2N9l4h3zg at public.gmane.org
Sun Jun 12 17:32:29 UTC 2005
On Sun, 12 Jun 2005 pking123-rieW9WUcm8FFJ04o6PK0Fg at public.gmane.org wrote:
> The following code segfaults under Cygwin:
> ...
> char *x;
> int func ()
> {
> *x = "something";
Yep, sure does. But the original poster didn't put that `*' in the
assignment. That one small change makes your code completely different
from his.
He set `x' to point to the literal string. Your version, well, is more
complicated. It tries to set the character that `x' points to. There
are two problems with this:
+ `x' has never been assigned a value, so where does it point? In fact,
since it's a global variable, it gets implicitly initialized to a zero
of the appropriate type, in this case a null pointer. But a null pointer
doesn't point anywhere!
+ The value being assigned to that character should be a character value
(that is, a single character). What your code tries to assign is a
string, that is, a pointer to an initialized *array* of characters. When
I give this code to GCC, it produces a warning message about that. The
pointer is being converted to an integer, and the result is being treated
as a character for purposes of the assignment.
C doesn't do array assignments, e.g. copying whole strings, with `='.
For that, you have to call strcpy().
Incidentally, the code as you showed it wouldn't even compile, since you
wrote "#indlude" instead of "#include" once. This presumably means you
retyped it rather than doing cut-and-paste or reading it from a file into
your mail message. That's a bad idea, because typos can make major
differences in how a program behaves; when asking about a programming
problem, it's very important to show *exactly* the code you tried to run.
> When I compiled your source code with a slight modification: single
> quotes around the %s...
> I got
> 'something
> '
> Note the \n came *before* the closing quote in the output but not in
> the printf().
That's peculiar, but I suspect that another typo might be at fault. I'm
not going to try to diagnose this one without seeing the exact code.
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
More information about the Legacy
mailing list