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-25 18:47

If you want to display the address of s[2], use the pointer specifier %p or arithmetic specifiers like %d, %i etc. The %s specifier takes a pointer and interprets the byte sequence found as ascii until NUL is encountered, which displays the string starting with the character at s[2].

Name: Anonymous 2013-06-25 19:22

>>13
&s[2] is the same as s+2 btw
you give the pointer to the third letter to %s which begins to read the string from it and to the end
are you dumb or what, pls go already

Name: Anonymous 2013-06-25 19:24

>>13
Pretty much, yes. The name of the array (in this case, s) is considered to be of pointer type in most contexts, thus evaluating to the address of the array's first element (in this case, a char with the value of 0x4D, meaning the letter 'M' when interpreted as ASCII).

If you want to display a string sitting in a char array, you use the specifier %s in the formatting literal, and just the array name as the following argument (the %s specifier, as mentioned, needs a pointer type to parse, and a name of an array happens to be treated as a pointer in this context, so no & operator is used). If you want to display just a part of the string, you use pointer arithmetic to point to the desired character, either like this

printf("%s", s + n); // n is the index of the starting char

or like this

printf("%s", &s[n]); // this is really just syntactic sugar for the above

If you want to see the address of a particular array element, you need to use specifers that show you a number, i.e. %d, %i etc. or %p (for the latter one you're best off casting the address to (void *), like this:

printf("%p", (void *)&s[n]);

If you're coming from java, pointers are a new concept to you - I recommend this as a solid introduction:

http://pweb.netcom.com/~tjensen/ptr/

It's especially important to understand what pointers and arrays have in common and what the differences are.

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