Re: How does this c - code work
From: Dave Neary (real.addressinthesig_at_thisoneis.invalid)
Date: 09/13/04
- Next message: Dave Neary: "Re: How does this c - code work"
- Previous message: Matthew: "Re: Qt 3 C++ Programming - very new - compilation problem -?"
- In reply to: David: "How does this c - code work"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 13 Sep 2004 21:02:41 GMT
Hi,
On 13 Sep 2004 02:52:00 -0700, David said:
> #include <stdio.h>
>
> int main()
> {
> char str[] = "Hello";
str is an array of characters (this is not the same as a char pointer,
as we will see).
> printf("%s\n", str);
When an array is used in an expression, it evaluates to a pointer to its
first element. In this case, you are passing &str[0] to printf (which is
fine, str[0] is a char *, which goes fine with the %s).
> printf("%s\n", &str);
Here, you are passing a pointer to the array (note the difference).
For example,
printf ("%s\n", &str + 1);
will pront garbage, because incrementing a pointer points to the next
object after the current one. Since the pointer is a pointer to an array
of size 6, you are actually going forward 6 bytes.
printf ("%s\n", str + 1);
would print "ello", though, since incrementing a char * goes on to the
next char.
However, since the address of the array is the same as the address of
its first member, the two evaluate to the same pointer value. When we
pass &str to printf, the %s format specifier means that printf
"pretends" that &str is a char *. So in printf, we end up with &str
being (char *)&str, which is more or less the same thing as str (or
&str[0], except that it's kind of undefined behaviour what happens when
you dereference an object not of type char* as a char*. However, doing
so as unsigned char * is fine. That said, you're usually in safe waters
with character types.
Cheers,
Dave.
--
David Neary,
E-Mail: bolsh at gimp dot org
Work e-mail: d dot neary at phenix dot fr
CV: http://dneary.free.fr/CV/
- Next message: Dave Neary: "Re: How does this c - code work"
- Previous message: Matthew: "Re: Qt 3 C++ Programming - very new - compilation problem -?"
- In reply to: David: "How does this c - code work"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|