Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Pointers in C

Name: Anonymous 2013-06-25 17:59

Hey guys I'm having a little trouble with the following example

#include <stdio.h>
int main(void)
{
char s[] = "Melbourne City";
printf("%s\n", &s[2]);
return 0;
}

which prints "lbourne City" instead of the address of letter 'l'.
I do understand that the %s in the printf continues until a null terminator is hit, but not why &s[2] returns a character in the first place.
Thanks.

Name: Anonymous 2013-06-28 16:32

>>77
>Why %u instead of %d when the argument is of int type?

>printf("\tvar: %u\n", var);
Stricly speaking, it should be %i (or %d, %x or %o to force a specific number base for the output). Still, it makes no difference here really, as var is assigned a positive value anyway (the storage format is the same for int and unsigned int, it merely depends on the interpretation whether the contents are considered unsigned or two's complement signed).

>printf("\tsizeof(arr): %u\n", (int)sizeof(arr));
Here, you definitely want an unsigned value, as a negative sizeof return value would not make much sense. Again, as the size of the array is merely 7, it does not make an actual difference. If on a 16-bit-integer system you had an array larger than 32k (or on a 32-bit-integer system an array larger than 2G), the expression (int)sizeof(arr) would return a negative value - however, the %u specifier in the string literal would recast it to unsigned int anyway. To be totally proper, the return value of sizeof should be cast from size_t to unsigned int in the first place:
 
printf("\tsizeof(arr): %u\n", (unsigned int)sizeof(arr));

>Are you Cudder?
I don't think so. Though, I already did happen to make some contributions to this rather amusing thread.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List